简体   繁体   English

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

[英]how to invert a dictionary with multiple same values?

I have a list of words I want to keep in a fast-to-extract data structure, so when a word is queried, I can return all of its anagrams. 我有一个要保留在快速提取数据结构中的单词列表,因此当查询单词时,我可以返回其所有字谜。 I thought of a dictionary with {(len, sum) : word} but I'm having a difficulty in implementing: 我想到了带有{(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))] #[OK] #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')] #[Not OK - (3,312) should be also mapped to "act", but this value was dropped] [((2, 207), 'an'), ((3, 312), 'cat'), ((3, 297), 'dad'), ((4, 425), 'home'), ((5, 545), 'horse'), ((5, 548), 'house'), ((3, 329), 'mom'), ((8, 872), 'ordinary')] #[不是OK-(3,312)也应映射为“ act”,但该值已删除]

How can I invert the dict so each value in the original dict will now be the key, but all matching key from original dict will be concatenated into a list of values in the new dict? 我该如何反转字典,以便原来字典中的每个值现在都成为键,但是原始字典中所有匹配的键都将串联到新字典中的值列表中?

Expected result: 预期结果:

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

You are losing values because the values of the original dict (which can have duplicates) becomes keys in this one. 您正在丢失值,因为原始字典( 可能有重复项)的值成为此字典中的键。 You could do something like 你可以做类似的事情

inverted = defaultdict(list)

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

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

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