创建一个词典(d3),该词典(d3)由其他两个词典(d1,d2)唯一的项目组成 [英] Create a dictionary (d3) consisting of items unique to two other dictionaries (d1, d2)

查看:219
本文介绍了创建一个词典(d3),该词典(d3)由其他两个词典(d1,d2)唯一的项目组成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里没主意. 我有:

I'm out of ideas here. I've got:

d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}

我想创建:

d3 = {4:70, 5:80, 6:90}

我意识到这很琐碎,因此感到沮丧.如果您有任何想法,请分享.

I realize how trivial this is, hence my frustration. If you've got any ideas, please share.

推荐答案

对称差异^查找唯一键.然后,这是一个简单的字典理解:

Symmetric difference ^ finds the unique keys. Then it's an easy dict comprehension:

>>> {k: d1.get(k, d2.get(k)) for k in (set(d1) ^ set(d2))}
{4: 70, 5: 80, 6: 90}

上面的方法是交叉兼容的代码.如果您不需要处理Python 2,它看起来会更好一些.

The method above is cross-compat code. It looks a bit nicer if you don't need to deal with Python 2:

>>> from collections import ChainMap
>>> d12 = ChainMap(d1, d2)
>>> {k: d12[k] for k in d1.keys() ^ d2.keys()}
{4: 70, 5: 80, 6: 90}

注意:此处的键"view"对象也可以在Python 2中的方法d.viewkeys()下使用.

Note: The keys "view" objects here are also available in Python 2 under the method d.viewkeys().

这篇关于创建一个词典(d3),该词典(d3)由其他两个词典(d1,d2)唯一的项目组成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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