如何反转具有多个相同值的字典?

时间:2018-10-03 09:32:31

标签: python dictionary

我有一个要保留在快速提取数据结构中的单词列表,因此当查询单词时,我可以返回其所有字谜。我想到了带有{(len, sum) : word}的字典,但是在实现时遇到了困难:

data = "mom, dad, house, home, cat, horse, an, ordinary, act" # note "cat" and "act" are anagrams
data = data.replace(" ", "") # remove whitespaces

d = {word : (len(word), sum(map(ord, word))) for word in data.split(",")}
print(sorted(d.items(), key=lambda k:k[1]))

#prints: [('an', (2, 207)), ('dad', (3, 297)), ('act', (3, 312)), ('cat', (3, 312)), ('mom', (3, 329)), ('home', (4, 425)), ('horse', (5, 545)), ('house', (5, 548)), ('ordinary', (8, 872))] #[确定]

inv_d = {v: k for k, v in d.items()}
print(sorted(inv_d.items(), key=lambda k:k[1]))

[((2, 207), 'an'), ((3, 312), 'cat'), ((3, 297), 'dad'), ((4, 425), 'home'), ((5, 545), 'horse'), ((5, 548), 'house'), ((3, 329), 'mom'), ((8, 872), 'ordinary')] #[不正确-(3,312)也应映射为“ act”,但该值已删除]

我该如何反转字典,以使原始字典中的每个值现在都成为键,但是原始字典中所有匹配的键都将被串联到新字典中的值列表中?

预期结果:

[((2, 207), 'an'), ((3, 312), ['cat', 'act']), ...]

1 个答案:

答案 0 :(得分:4)

您正在丢失值,因为原始字典的值(可以具有重复项)成为该值的键。你可以做类似的事情

inverted = defaultdict(list)

for key, value in original_dict.items():
    inverted[value].append(key)