2014-07-23 69 views
0

我有一本字典。使用python进行字典操作

dict = {'A':['a', 'b'], 'B':['c', 'b', 'a'], 'C':['d', 'c'], } 

什么是简单的方法从字典的键找出相似的值?

output : 

A&B : 'a', 'b' 
A&C : None 
B&C : 'c' 

这是如何实现的?

+0

随着你的清单内容是哈希的,例如尝试'设置(字典[ 'A'])。交叉点(字典[ 'B'])'。不过,你不应该调用你自己的对象'dict'。 – jonrsharpe

回答

2

使用set & other_set operator or set.intersectionitertools.combinations

>>> import itertools 
>>> 
>>> d = {'A':['a', 'b'], 'B':['c', 'b', 'a'], 'C':['d', 'c'], } 
>>> for a, b in itertools.combinations(d, 2): 
...  common = set(d[a]) & set(d[b]) 
...  print('{}&{}: {}'.format(a, b, common)) 
... 
A&C: set() 
A&B: {'b', 'a'} 
C&B: {'c'} 
+0

以及如果我想获得差异怎么办? – sam

+0

使用'set(..) - set(..)'或'set(..)。difference(set(..))'。请参阅['set.difference'](https://docs.python.org/3/library/stdtypes.html#set.difference) – falsetru

+0

谢谢我将接受回答 – sam

9
In [1]: dct = {'A':['a', 'b'], 'B':['c', 'b', 'a'], 'C':['d', 'c'], } 

In [2]: set(dct['A']).intersection(dct['B']) 
Out[2]: {'a', 'b'} 

In [3]: set(dct['A']).intersection(dct['C']) 
Out[3]: set() 

In [4]: set(dct['B']).intersection(dct['C']) 
Out[4]: {'c'}