Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to update the values of a dictionary dynamically in python from a tuple

I thought about a small python exercise today, how would someone dynamically update the dictionary values in array from a tuple.

I have the following dictionary:

people = [
 {"first_name": "Jane", "last_name": "Watson", "age": 28},
 {"first_name": "Robert", "last_name": "Williams", "age": 34},
 {"first_name": "Adam", "last_name": "Barry", "age": 27}
]

now i have a list of tuple:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

new_names = [("Richard", "Martinez"), ("Justin", "Hutchinson"), ("Candace", "Garrett")]

I have tried this approach:

for person in people:
  for name in new_names:
    person["first_name"] = name
    person["last_name"] = name

but its wrong because it give me the same values everywhere

[{'age': 28,
  'first_name': ('Candace', 'Garrett'),
  'last_name': ('Candace', 'Garrett')},
 {'age': 34,
  'first_name': ('Candace', 'Garrett'),
  'last_name': ('Candace', 'Garrett')},
 {'age': 27,
  'first_name': ('Candace', 'Garrett'),
  'last_name': ('Candace', 'Garrett')}]

How can i update the first_name and last_name with the tuples data above?

>Solution :

Your example:

for person in people:
  for name in new_names:
    person["first_name"] = name
    person["last_name"] = name

Is assigning the name to every dictionary, as it is nested below for person in people. I suggest stepping through your code to see what is happening.

It is also assigning both first_name and last_name with the entire tuple. You need to do something like:

person["first_name"] = name[0]
person["last_name"] = name[1]

This example fixes both issues:

for d, name in zip(people, new_names):
    # Assuming the length of new_names and people is the same
    d["first_name"] = name[0]
    d["last_name"] = name[1]
[{'age': 28, 'first_name': 'Richard', 'last_name': 'Martinez'},
 {'age': 34, 'first_name': 'Justin', 'last_name': 'Hutchinson'},
 {'age': 27, 'first_name': 'Candace', 'last_name': 'Garrett'}]

zip creates a iterator (tuple-ish) that is unpacked for iterating with multiple variables in parallel

zip example in SO

zip on W3

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading