简体   繁体   English

python使用相同长度的另一个列表更新字典列表

[英]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 我想知道是否有更有效/简洁的方法

Could try using zip() : 可以尝试使用zip()

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

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)

check here 在这里检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM