Reputation: 7448
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
Reputation: 923
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female', 'Age': 17 }
dict.update(dict2)
Upvotes: 0
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