0

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?

feldo badix
  • 115
  • 1
  • 12
  • iterate over `new_names` like `for person in new_names:` and then append the items to your `people` var like `people.append({"first_name": person[0], "last_name": person[1])` – Bijay Regmi Apr 20 '22 at 11:36

1 Answers1

2

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

Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29
  • interesting, i didnt know that you could iterate through zip like without using list or dict, i mean `list(zip(...)`. anyway thanks – feldo badix Apr 20 '22 at 11:58
  • No worries @feldobadix. Note that `zip` is an iterator, so you can only iterate over it once. You can use `list(zip(...))` to save it for later on – Freddy Mcloughlan Apr 20 '22 at 12:07