Rose
Rose

Reputation: 45

How do you join a list to a dictionary of lists as a new item - python?

Maybe a simple question:

In python I have a list of dictionaries and I want to add a list as new item in every dictionary in the list?

For example I have the list of dictionaries:

list_dict =[{'id':1, 'text':'John'},
            {'id':2, 'text':'Amy'},
            {'id':3, 'text':'Ron'}]

And a list:

list_age = [23, 54, 41]

How could I then add the list to produce the list of dictionaries:

list_dict =[{'id':1, 'text':'John', 'age':23},
            {'id':2, 'text':'Amy', 'age':54},
            {'id':3, 'text':'Ron', 'age':41}]

I am unsure of the correct code to use here?

Upvotes: 1

Views: 99

Answers (4)

Uthishsethuraman k
Uthishsethuraman k

Reputation: 1

Add the list to produce the list of dictionaries:

for a, b in zip(list_dict, list_englishmark):
    a["englishmark"] = b

print(list_dict)

Output:

[{'id': 1, 'name': 'mari', 'englishmark': 80}, {'id': 2, 'name': 'Arun', 'englishmark': 54}, {'id': 3, 'name': 'ram', 'englishmark':75}]

Upvotes: 0

Charis Moutafidis
Charis Moutafidis

Reputation: 363

Something like this could work

for index, item in enumerate(list_age):
  list_dict[index]['age'] = item

Edit: As @Netwave mentioned, you should make sure that len(list_age) is not greater than len(list_dict).

Upvotes: 2

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6935

Try this loop if list_age and list_dict are of same length :

for i, j in zip(list_dict, list_age):
  i['age']=j

OUTPUT :

[{'id': 1, 'text': 'John', 'age': 23}, {'id': 2, 'text': 'Amy', 'age': 54}, {'id': 3, 'text': 'Ron', 'age': 41}]

Upvotes: 2

Netwave
Netwave

Reputation: 42746

Use zip, to iterate over the matching pairs and update the dicts:

>>> for d, a in zip(list_dict, list_age):
...     d["age"] = a
... 
>>> list_dict
[{'id': 1, 'text': 'John', 'age': 23}, {'id': 2, 'text': 'Amy', 'age': 54}, {'id': 3, 'text': 'Ron', 'age': 41}]

Upvotes: 3

Related Questions