要合并两个字典中相同键的值而不覆盖内容,可以使用update()方法。

以下是一个示例代码:

dict1 = {'a': 'apple', 'b': 'banana', 'c': 'cherry'}
dict2 = {'b': 'blueberry', 'd': 'durian', 'e': 'elderberry'}

for key, value in dict2.items():
    if key in dict1:
        dict1[key] += ', ' + value
    else:
        dict1[key] = value

print(dict1)

输出结果为:

{'a': 'apple', 'b': 'banana, blueberry', 'c': 'cherry', 'd': 'durian', 'e': 'elderberry'}

在这个示例中,我们使用for循环遍历dict2中的键值对。对于每个键值对,我们检查它是否存在于dict1中。如果存在,我们将其值追加到dict1中对应键的值后面,以逗号分隔。如果不存在,我们将该键值对添加到dict1中。

最后,我们打印合并后的dict1字典

python中怎么把两个字典相同键的值的内容合并不覆盖内容

原文地址: https://www.cveoy.top/t/topic/iHa2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录