合并两个字典,并在Python中保留重复键的值 [英] Merge two dictionaries and keep the values for duplicate keys in Python

查看:1351
本文介绍了合并两个字典,并在Python中保留重复键的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有两个字典:

Let's suppose that I have two dictionaries:

dic1 =  { "first":1, "second":4, "third":8} 
dic2 =  { "first":9, "second":5, "fourth":3}

是否有一种简单的方法来获取类似于以下内容的内容?

Is there a straightforward way to obtain something like the below?

dic3 =  { "first":[1,9], "second":[4,5], "third":[8], "fourth":[3]}

我使用列表来存储值,但是元组也可以.

I used lists to store values, but tuples are fine as well.

推荐答案

通常来说,将不同键的值转换为不同的对象类型是一种不好的做法.我只会做类似的事情:

In general, I would say it's bad practice to cast the values of different keys as different object types. I would simply do something like:

def merge_values(val1, val2):
    if val1 is None:
        return [val2]
    elif val2 is None:
        return [val1]
    else:
        return [val1, val2]
dict3 = {
    key: merge_values(dic1.get(key), dic2.get(key))
    for key in set(dic1).union(dic2)
}

这篇关于合并两个字典,并在Python中保留重复键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆