[英]Change the value of a dictionary to key of a dictionary in python
我想創建一個“真正的”字典:荷蘭語到英語字典,其中包含以下單詞:def reversTranslation(dictionary):
>>> dictionary= {'tension': ['spanning'], 'voltage': ['spanning', 'voltage']}
>>> dictionary= reverseTranslation(dictionary)
>>> dictionary
{'spanning': ['tension', 'voltage'], 'voltage': ['voltage']}
你可以在荷蘭語中看到“跨越”在英語中有兩種不同的含義。 幫助將不勝感激。
干得好:
def reverseTranslation(d):
return dict((v1,[k for k,v in d.iteritems() if v1 in v])
for v1 in set(sum(d.values(),[])))
如果您詢問如何獲得該結果,最可讀的方式是:
from collections import defaultdict
def reverse_dictionary(dictionary):
result = defaultdict(list)
for key, meanings in dictionary.iteritems(): #or just .items()
for meaning in meanings:
result[meaning].append(key)
return result
或者您可以先對值進行總結,然后對字典進行迭代。
d= {'tension': ['spanning'], 'voltage': ['spanning', 'voltage'],'extra':['voltage']}
val = set(reduce(list.__add__,d.values()))
dict={}
for x in val:
tmp={x:[]}
for k,v in d.items():
if x in v:
tmp[x].append(k)
dict.update(tmp)
print dict
注意:集合僅在python 2.4及更高版本中可用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.