gpt4 book ai didi

python - 在 python 字典中插入或更新键

转载 作者:太空狗 更新时间:2023-10-29 20:54:40 26 4
gpt4 key购买 nike

我有一个 python 字典 dict1,它有超过 20,000 个键,我想用另一个字典 dict2 更新它。字典看起来像这样:

dict1
key11=>[value11]
key12=>[value12]
...
...
keyxyz=>[value1x] //common key
...... so on

dict2
key21=>[value21]
key22=>[value22]
...
...
keyxyz=>[value2x] // common key
........ so on

如果我用

dict1.update(dict2)

然后 dict1 的键与 dict2 的键相似,它们的值将被 dict2 的值覆盖。我想要的是,如果一个键已经存在于 dict1 中,那么应该将 dict2 中该键的值附加到 dict1 的值。所以

dict1.conditionalUpdate(dict2)

应该导致

dict1
key11=>[value11]
key12=>[value12]
key21=>[value21]
key22=>[value22]
...
...
keyxyz=>[value1x,value2x]

一个简单的方法是为 dict1 的每个键迭代 dict2 的键并插入或更新键。有更好的方法吗? python 是否支持支持这种功能的内置数据结构?

最佳答案

使用defaultdict来自收藏模块。

>>> from collections import defaultdict
>>> dict1 = {1:'a',2:'b',3:'c'}
>>> dict2 = {1:'hello', 4:'four', 5:'five'}
>>> my_dict = defaultdict(list)
>>> for k in dict1:
... my_dict[k].append(dict1[k])
...
>>> for k in dict2:
... my_dict[k].append(dict2[k])
...
>>> my_dict[1]
['a', 'hello']

关于python - 在 python 字典中插入或更新键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10635052/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com