2011-02-04 53 views
10

我對Python中的字典有疑問。通過相同的值在字典中查找所有鍵元素

那就是:

我有一個像dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' }

的字典現在我想用相同的值來獲得所有關鍵元素和它保存在一個新的字典。

新詞典應該是這樣的:

new_dict = { 'b':('cdf'), 'a':('abc','gh'), 'g':('fh','hfz')}

+6

不要使用「dict」作爲變量名稱,因爲它是內建函數的名稱。 – 2011-02-04 16:29:22

回答

20

如果你是罰款名單,而不是在新的字典元組,你可以使用

from collections import defaultdict 
some_dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' } 
new_dict = defaultdict(list) 
for k, v in some_dict.iteritems(): 
    new_dict[v].append(k) 

如果你想避免使用defaultdict,你也可以做

new_dict = {} 
for k, v in some_dict.iteritems(): 
    new_dict.setdefault(v, []).append(k) 
2

這是一個天真的實現。有更好的Python技能的人可能會使它更簡潔,更棒。

dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' } 

new_dict = {} 
for pair in dict.items(): 
    if pair[1] not in new_dict.keys(): 
     new_dict[pair[1]] = [] 

    new_dict[pair[1]].append(pair[0]) 

print new_dict 

這將產生

{'a': ['abc', 'gh'], 'b': ['cdf'], 'g': ['fh', 'hfz']} 
0

如果你特別希望在新的字典元組的值,您仍然可以使用defaultdict,並使用元組串聯。該解決方案可以在Python 3.4+:

from collections import defaultdict 

source = {'abc': 'a', 'cdf': 'b', 'gh': 'a', 'fh': 'g', 'hfz': 'g'} 
target = defaultdict(tuple) 

for key in source: 
    target[source[key]] += (key,) 

print(target) 

將產生

defaultdict(<class 'tuple'>, {'a': ('abc', 'gh'), 'g': ('fh', 'hfz'), 'b': ('cdf',)}) 

這可能比通過生成列表插入一個字典較慢,並會創造更多的對象被收集。所以,你可以建立你的字典出清單,然後將其映射到元組:

target2 = defaultdict(list) 

for key in source: 
    target2[source[key]].append(key) 

for key in target2: 
    target2[key] = tuple(target2[key]) 

print(target2) 

,這將給同樣的結果如上。

相關問題