Python中dict对象的联合 [英] Union of dict objects in Python

查看:30
本文介绍了Python中dict对象的联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你如何在 Python 中计算两个 dict 对象的并集,其中 (key, value) 对出现在结果中 iff keyin 任一字典(除非有重复)?

How do you calculate the union of two dict objects in Python, where a (key, value) pair is present in the result iff key is in either dict (unless there are duplicates)?

例如 {'a' : 0, 'b' : 1}{'c' : 2} 的并集是 {'a' : 0, 'b' : 1, 'c' : 2}.

For example, the union of {'a' : 0, 'b' : 1} and {'c' : 2} is {'a' : 0, 'b' : 1, 'c' : 2}.

最好在不修改任一输入 dict 的情况下执行此操作.这是有用的示例:Get当前作用域内的所有变量及其值的字典

Preferably you can do this without modifying either input dict. Example of where this is useful: Get a dict of all variables currently in scope and their values

推荐答案

这个问题提供一个习语.您使用其中一个字典作为 dict() 构造函数的关键字参数:

This question provides an idiom. You use one of the dicts as keyword arguments to the dict() constructor:

dict(y, **x)

重复的解析有利于 x 中的值;例如

Duplicates are resolved in favor of the value in x; for example

dict({'a' : 'y[a]'}, **{'a', 'x[a]'}) == {'a' : 'x[a]'}

这篇关于Python中dict对象的联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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