简体   繁体   English

在python中将字典的值更改为字典的键

[英]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): 我想创建一个“真正的”字典:荷兰语到英语字典,其中包含以下单词: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. 帮助将不胜感激。

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(),[])))

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. 或者您可以先对值进行总结,然后对字典进行迭代。

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 注意:集合仅在python 2.4及更高版本中可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM