knowledgealways
knowledgealways

Reputation: 29

Python Update value in key in an object, from list

I'm a beginner at Python and maybe I am trying to do something a little complex - I don't know. I'm scratching my brain on how to do this and what the right way would be to go about it, i.e. proper steps?

Below is what I have is a Dictionary as such:

[{'\id':'001', 
  'second_id':'0001', 
  'imp_url':"https://urlone.com", 
  'last_id':'00001'},

  {'\id':'002', 
  'second_id':'0002', 
  'imp_url':"https://urltwo.com", 
  'last_id':'00002'}
 ]

And here is my List:

['imp_url', '["https://urltestx.com", "https://urltestxx.com"]']

Desired result is an updated object that would have updated values* for the key "imp_url", which exist in the List(above). Like so:

Desired result:

[{'\id':'001', 
  'second_id':'0001', 
  'imp_url':'["https://urltestx.com"]', 
  'last_id':'00001'},

  {'\id':'002', 
  'second_id':'0002', 
  'imp_url':'["https://urltestxx.com"]', 
  'last_id':'00002'}
 ]

Note* - Brackets and single quotes are kept in updated desired result.

I hope that made sense. I tried using dict with zip, then went down a rabbit hole of frozensets? I'm pretty sure I need to create a new Dict but how can I can update an object from values in an array to specific key? I also tried using .update() but that seemed to work with integers as key and not necessarily words as keys. I also don't know about Tuples yet.

Is there a method to do this?

Any assistance would be really helpful! Little lost ... Thank you all -

Upvotes: 0

Views: 1131

Answers (1)

python_user
python_user

Reputation: 7113

You were in the right direction, you can use ast.literal_eval to make the second element of your list into an actual list.

seq = [{'\id':'001', 
  'second_id':'0001', 
  'imp_url':"https://urlone.com", 
  'last_id':'00001'},

  {'\id':'002', 
  'second_id':'0002', 
  'imp_url':"https://urltwo.com", 
  'last_id':'00002'}
 ]

from ast import literal_eval

new_list = ['imp_url', '["https://urltestx.com", "https://urltestxx.com"]']
new_list[-1] = literal_eval(new_list[-1])


for d, url in zip(seq, new_list[-1]):
    d[new_list[0]] = f'["{url}"]'

print(seq)

Output

[{'\\id': '001',
  'second_id': '0001',
  'imp_url': '["https://urltestx.com"]',
  'last_id': '00001'},
 {'\\id': '002',
  'second_id': '0002',
  'imp_url': '["https://urltestxx.com"]',
  'last_id': '00002'}]

Upvotes: 1

Related Questions