所以我想尝试将某些键从一个字典合并到另一个字典,这样做
a = {'a':2, 'b':3, 'c':5}
b = {'d':2, 'e':4}
a.update(b)
>>> a
{'a': 2, 'c': 5, 'b': 3, 'e': 4, 'd': 2} # returns a merge of all keys
但是说你只想要键和值对'd':2而不是字典中的所有元素如何才能实现这一点:
{'a': 2, 'c': 5, 'b': 3, 'd': 2}
答案 0 :(得分:2)
如果您知道要使用a
更新b['d']
,请使用:
a['d'] = b['d']
答案 1 :(得分:0)
我不知道我是否得到了你所要求的东西。无论如何,如果你想用另一个键更新字典上的某些键,你可以这样做:
a['d'] = b['d']
或者,如果您想更新多个密钥:
for to_update in keys_to_update: # keys_to_update is a list
a[to_update] = b[to_update]
答案 2 :(得分:0)
您可以使用以下代码段:
a = {'a':2, 'b':3, 'c':5}
b = {'d':2, 'e':4}
desiredKeys = ('d',)
for key, val in b.items():
if key in desiredKeys:
a[key] = b[key]
print( a )
上面的示例将输出:
{'d': 2, 'b': 3, 'c': 5, 'a': 2}