Change the value of a dictionary to key of a dicti

2019-09-05 13:53发布

I want to create a "real" dictionary: a Dutch to English dictionary with the following words: def reversTranslation(dictionary):

>>> dictionary= {'tension': ['spanning'], 'voltage': ['spanning', 'voltage']}
>>> dictionary= reverseTranslation(dictionary)
>>> dictionary
{'spanning': ['tension', 'voltage'], 'voltage': ['voltage']}

As you can see in dutch 'spanning' has two different meanings in English. Help will be appreciated.

3条回答
Explosion°爆炸
2楼-- · 2019-09-05 14:05
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

Note: collections are available only from python 2.4 and later

查看更多
对你真心纯属浪费
3楼-- · 2019-09-05 14:14

If you are asking how to obtain that result, the most readable way is:

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

Or you can first sum up the values and then iterate on the dictionary.

查看更多
Rolldiameter
4楼-- · 2019-09-05 14:16

Here you go:

def reverseTranslation(d):
    return dict((v1,[k for k,v in d.iteritems() if v1 in v])
                for v1 in set(sum(d.values(),[])))
查看更多
登录 后发表回答