daiyue
daiyue

Reputation: 7448

python update a list of dictionaries using another list of the same length

I am trying to update a list a of dictionaries using another list b of the same length that each dict should add a key which corresponds to a value in b at the same position,

for x in range(len(a)):
    a[x]['val'] = b[x]

I am wondering is there a more efficient/concise way to do it

Upvotes: 2

Views: 66

Answers (3)

Tiago_nes
Tiago_nes

Reputation: 923

#!/usr/bin/python

dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female', 'Age': 17 }

dict.update(dict2)

check here

Upvotes: 0

eugenhu
eugenhu

Reputation: 1238

Could try using zip():

for ai, bi in zip(a, b):
    ai["val"] = bi

Upvotes: 3

Carles Mitjans
Carles Mitjans

Reputation: 4866

If you are using python 3.x, you can use a list comprehension to create the new list on the fly:

a = [{'A': 1}, {'B': 2}]
b = [3,4]
[{**d, **{"val":b[i]}} for i, d in enumerate(a)]

Output:

[{'A': 1, 'val': 3}, {'B': 2, 'val': 4}]

Notice, though, that this doesn't apply on python 2.7. Another option would be to use a list comprehension to update each dictionary:

>>> a = [{'A': 1}, {'B': 2}]
>>> b = [3, 4]
>>> [x.update({"val":b[i]}) for i,x in enumerate(a)]
[None, None]
>>> a
[{'A': 1, 'val': 3}, {'B': 2, 'val': 4}]

Upvotes: 0

Related Questions