Home > Back-end >  how to update the values of a dictionary dynamically in python from a tuple
how to update the values of a dictionary dynamically in python from a tuple

Time:04-21

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:

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?

CodePudding user response:

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

  • Related