2014-07-23 62 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'}