Python - 在两个dicts中查找非共同项

时间:2020-11-29 18:09:35

Lets say I have two dictionaries:

假设我有两个词典:

a = {'a': 1, 'b': 2, 'c': 3}
b = {'b': 2, 'c': 3, 'd': 4, 'e': 5}

What's the most pythonic way to find the non mutual items between the two of them such that for a and b I would get:

什么是找到两者之间的非相互项目的最pythonic方式,这样对于a和b我会得到:

{'a': 1, 'd': 4, 'e': 5}

I had thought:

我以为:

{key: b[key] for key in b if not a.get(key)}

but that only goes one way (b items not in a) and

但这只是一种方式(b项不在a)和

a_only = {key: a[key] for key in a if not b.get(key)}.items()
b_only = {key: b[key] for key in b if not a.get(key)}.items()

dict(a_only + b_only)

seams very messy. Any other solutions?

接缝非常凌乱。还有其他方法吗?

4 个解决方案

#1


11  

>>> dict(set(a.iteritems()) ^ set(b.iteritems()))
{'a': 1, 'e': 5, 'd': 4}

#2


3  

Try with the symetric difference of set() :

尝试使用set()的对称差异:

out = {}
for key in set(a.keys()) ^ set(b.keys()):
   out[key] = a.get(key, b.get(key))

#3


2  

diff = {key: a[key] for key in a if key not in b}
diff.update((key,b[key]) for key in b if key not in a)

just a bit cheaper version of what you have.

你只需要更便宜的版本。

#4


0  

>>> a = {'a': 1, 'b': 2, 'c': 3}
>>> b = {'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> keys = set(a.keys()).symmetric_difference(set(b.keys()))
>>> result = {}
>>> for k in keys: result[k] = a.get(k, b.get(k))
... 
>>> result
{'a': 1, 'e': 5, 'd': 4}

Whether this is less messy than your version is debatable, but at least it doesn't re-implement symmetric_difference.

这是否比你的版本更简洁是值得商榷的,但至少它不会重新实现symmetric_difference。

#1


11  

>>> dict(set(a.iteritems()) ^ set(b.iteritems()))
{'a': 1, 'e': 5, 'd': 4}

#2


3  

Try with the symetric difference of set() :

尝试使用set()的对称差异:

out = {}
for key in set(a.keys()) ^ set(b.keys()):
   out[key] = a.get(key, b.get(key))

#3


2  

diff = {key: a[key] for key in a if key not in b}
diff.update((key,b[key]) for key in b if key not in a)

just a bit cheaper version of what you have.

你只需要更便宜的版本。

#4


0  

>>> a = {'a': 1, 'b': 2, 'c': 3}
>>> b = {'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> keys = set(a.keys()).symmetric_difference(set(b.keys()))
>>> result = {}
>>> for k in keys: result[k] = a.get(k, b.get(k))
... 
>>> result
{'a': 1, 'e': 5, 'd': 4}

Whether this is less messy than your version is debatable, but at least it doesn't re-implement symmetric_difference.

这是否比你的版本更简洁是值得商榷的,但至少它不会重新实现symmetric_difference。