如何在Python中反转字典(其值为列表)?

时间:2016-03-11 16:40:04

标签: python python-3.x dictionary

我想编写一个接收字典作为输入参数的函数,并返回输入字典的反转,其中原始字典的值用作返回字典的键,原始字典的键用作返回字典的值,如下所述:

dict = {'Accurate': ['exact', 'precise'], 
        'exact': ['precise'], 
        'astute': ['Smart', 'clever'], 
        'smart': ['clever', 'bright', 'talented']}

dict = {'precise': ['accurate', 'exact'], 
        'clever': ['astute', 'smart'], 
        'talented': ['smart'], 
        'bright': ['smart'],
        'exact': ['accurate'],
        'smart': ['astute']}

返回字典中的值列表应按升序排序。资本化并不重要。这意味着所有单词都应转换为小写字母。例如,单词" Accurate"在原始字典中大写,但在返回的字典中,它使用全部小写字母书写。

#My code is:
from collections import defaultdict
def reverse_dictionary(input_dict):
   d = defaultdict(list)
   for v,k in input_dict.items():
       d[k].append(v)
       return d

但它会返回此错误:

Error in evaluating function:
TypeError at line 6
unhashable type: 'list'

6 个答案:

答案 0 :(得分:10)

你可以这么简单地做到这一点:

newdict = {}
for key, value in olddict.items():
    for string in value:
        newdict.setdefault(string, []).append(key)

答案 1 :(得分:4)

我首先使用默认字典交换键/值:

output_dict = defaultdict(list)
for key, values in input_dict.items():
    for value in values:
        output_dict[value.lower()].append(key.lower())

最后排序:

for key, values in output_dict.items():
    output_dict[key] = sorted(values)

答案 2 :(得分:4)

使用词典理解!

>>> evil_petting_zoo = {'bear':3, 'crocodile':1,'kangaroo':2,'goat':0}
>>> evil_petting_zoo.items()

dict_items([('bear', 3), ('crocodile', 1), ('kangaroo', 2), ('goat', 0)])

>>> {i[1]:i[0] for i in evil_petting_zoo.items()}

{3: 'bear', 1: 'crocodile', 2: 'kangaroo', 0: 'goat'}

TL; DR:

{i[1]:i[0] for i in myDictionary.items()}

答案 3 :(得分:1)

我如何反转字典:

def reverse(org):
    return {v: k for k, v in org.items()}

print(reverse({1: 'a', 2: 'b'}))
# {'a': 1, 'b': 2}

答案 4 :(得分:1)

为了热爱函数式编程,这是一种有趣的方式:

from itertools import product
from more_itertools import map_reduce, flatten

olddict =  {'Accurate': ['exact', 'precise'], 
        'exact': ['precise'], 
        'astute': ['Smart', 'clever'], 
        'smart': ['clever', 'bright', 'talented']}

value_key_pairs = flatten(product(v,(k,)) for k,v in olddict.items())
out = map_reduce(value_key_pairs, lambda k:k[0].lower(), lambda k:k[1].lower())

assert dict(out) == {'exact': ['accurate'], 'precise': ['accurate', 'exact'], 'smart': ['astute'], 'clever': ['astute', 'smart'], 'bright': ['smart'], 'talented': ['smart']}

答案 5 :(得分:0)

这是答案,不使用任何模块:

def reverse_dictionary(input_dict):
    out = {}
    for v in input_dict.values():  
        for value in v:
            if value not in out:
                out[value.lower()] = []
    for i in input_dict:
        for j in out:
            if j in map (lambda x : x.lower(),input_dict[i]):
                out[j].append(i.lower())
                out[j].sort()
    return out