0

所以我想尝试只将某些键从一个字典合并到另一个字典

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}
4

3 回答 3

2

如果您知道要使用 更新a,请b['d']使用以下命令:

a['d'] = b['d']
于 2013-04-30T13:41:49.250 回答
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}
于 2013-04-30T13:48:34.570 回答
0

我不知道我是否明白你的要求。无论如何,如果您只想用另一个键更新字典中的某些键,您可以执行以下操作:

a['d'] = b['d']

或者,如果您想更新多个密钥:

for to_update in keys_to_update: # keys_to_update is a list
    a[to_update] = b[to_update]
于 2013-04-30T13:44:58.567 回答