Change The Value Of A Dictionary To Key Of A Dictionary In Python
I want to create a 'real' dictionary: a Dutch to English dictionary with the following words: def reversTranslation(dictionary): >>> dictionary= {'tension': ['spanning'],
Solution 1:
Here you go:
defreverseTranslation(d):
returndict((v1,[k for k,v in d.iteritems() if v1 in v])
for v1 inset(sum(d.values(),[])))
Solution 2:
If you are asking how to obtain that result, the most readable way is:
from collections import defaultdict
defreverse_dictionary(dictionary):
result = defaultdict(list)
for key, meanings in dictionary.iteritems(): #or just .items()for meaning in meanings:
result[meaning].append(key)
return result
Or you can first sum up the values and then iterate on the dictionary.
Solution 3:
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)
printdict
Note: collections are available only from python 2.4 and later
Post a Comment for "Change The Value Of A Dictionary To Key Of A Dictionary In Python"