[英]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, 我试图更新列表
a
用另一个列表字典b
每个字典应增加相当于一键的值相同长度的b
在相同的位置,
for x in range(len(a)):
a[x]['val'] = b[x]
I am wondering is there a more efficient/concise way to do it 我想知道是否有更有效/简洁的方法
If you are using python 3.x, you can use a list comprehension to create the new list on the fly: 如果您使用的是python 3.x,则可以使用列表推导来即时创建新列表:
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. 但是请注意,这不适用于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}]
#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7}
dict2 = {'Sex': 'female', 'Age': 17 }
dict.update(dict2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.