在Python中合并两个dict的值列表[重复]

t3psigkw  于 4个月前  发布在  Python
关注(0)|答案(2)|浏览(75)

此问题在此处已有答案

How to merge dicts, collecting values from matching keys?(18个答案)
2天前关闭。
我有几个字典的键都相等。键的值是列表。现在我将合并值列表,如。
输入,例如:

dict_1 ={"a":["1"], "b":["3"]}
dict_2 = {"a":["2"], "b":["3"]}

字符串
所需输出:

new_dict = {'a':["1","2"], 'b':["3","3"]}


什么是最快的,pythonic的方法来获得这个结果?
我找到了这个,但这并不能满足我的需求:

merged_dic = {**dict_1, **dict_2}


和其他人,但没有解决我的愿望.有没有一个内置的函数没有循环在每个元素,因为我有很多字典和更复杂的我上面的例子?感谢任何帮助!

rkkpypqq

rkkpypqq1#

你可以像这样使用defaultdictextend

from collections import defaultdict

new_dict = defaultdict(list)
for d in [dict_1, dict_2]:
    for key, value in d.items():
        new_dict[key].extend(value)

字符串

oxf4rvwz

oxf4rvwz2#

如果您的字典具有相同的键,则可以使用Collections中的Counter

from collections import Counter

dict_1 = {"a": ["1"], "b": ["3"]}
dict_2 = {"a": ["2"], "b": ["3"]}

# Use Counter to merge the dictionaries
new_dict = Counter(dict_1)
new_dict.update(dict_2)

# Convert the Counter back to a dictionary
new_dict = dict(new_dict)

字符串
Or/ If else编写自己的函数

dict_1 = {"a": ["1"], "b": ["3"]}
dict_2 = {"a": ["2"], "b": ["3"]}

new_dict = {}

# Iterate over the keys of both dictionaries
for key in set(dict_1.keys()) | set(dict_2.keys()):
    # Merge the lists if the key is present in both dictionaries
    new_dict[key] = dict_1.get(key, []) + dict_2.get(key, [])

相关问题