6

I'd like to build a dictionary in python in which different keys refer to the same element. I have this dictionary:

persons = {"George":'G.MacDonald', "Luke":'G.MacDonald', "Larry":'G.MacDonald'} 

the key refer all to an identical string but the strings have different memory location inside the program, I'd like to make a dictionary in which all these keys refer to the same element, is that possible?

4

2 回答 2

5

您可以执行以下操作:

import itertools as it

unique_dict = {}
value_key=lambda x: x[1]
sorted_items = sorted(your_current_dict.items(), key=value_key)
for value, group in it.groupby(sorted_items, key=value_key):
    for key in group:
        unique_dict[key] = value

这会将您的字典转换为任何类型(但可比较)的相等值都是唯一的字典。如果您的值不可比较(但可散列),您可以使用临时值dict

from collections import defaultdict
unique_dict = {}
tmp_dict = defaultdict(list)

for key, value in your_current_dict.items():
    tmp_dict[value].append(key)

for value, keys in tmp_dict.items():
    unique_dict.update(zip(keys, [value] * len(keys)))
于 2013-04-21T08:56:50.683 回答
2

如果你碰巧使用的是 python 3,sys.intern提供了一个非常优雅的解决方案:

for k in persons:
    persons[k] = sys.intern(persons[k])

在 Python 2.7 中,您可以通过一个额外的步骤来做大致相同的事情:

interned = { v:v for v in set(persons.itervalues()) }
for k in persons:
    persons[k] = interned[persons[k]]

interned = dict( (v, v) for … )在 2.x (< 2.7) 中,您可以改为编写。

于 2013-07-31T03:40:37.350 回答