2个Python字典如何变为1? [英] How can 2 Python dictionaries become 1?

查看:183
本文介绍了2个Python字典如何变为1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Python扩展对于字典

我知道Python列表可以被附加或扩展。有没有一个简单的方法来组合两个Python字典与唯一的键,例如:

I know that Python list can be appended or extended. Is there an easy way to combine two Python dictionaries with unique keys, for instance:

basket_one = {'fruit': 'watermelon', 'veggie': 'pumpkin'}
basket_two = {'dairy': 'cheese', 'meat': 'turkey'}

然后我想要一大块食物:

I then want one big basket of food:

basket = {
    'fruit': 'watermelon', 
    'veggie': 'pumpkin', 
    'dairy': 'cheese', 
    'meat': 'turkey'
}

如何在Python中执行上述?

How can I perform the above in Python?

推荐答案

basket = dict(basket_one, **basket_two)

如有冲突, c $ c> basket_two 将覆盖 basket_one 中的那些。随着一线游戏的进行,这是非常可读和透明的,我无时间地使用任何一个混合使用它的人可以派上用场(任何读者无法理解它,实际上都会很好地服务于这种提示他或听到的方式来学习 dict ** form ;-)。所以,例如,使用如下:

In case of conflict, the items from basket_two will override the ones from basket_one. As one-liners go, this is pretty readable and transparent, and I have no compunction against using it any time a dict that's a mix of two others comes in handy (any reader who has trouble understanding it will in fact be very well served by the way this prompts him or hear towards learning about dict and the ** form;-). So, for example, uses like:

x = mungesomedict(dict(adict, **anotherdict))

在我的代码中相当频繁地出现。

are reasonably frequent occurrences in my code.

这篇关于2个Python字典如何变为1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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