简体   繁体   English

python词典中的多个键是可能的吗?

[英]multiple keys in python dictionary, is possible?

I'd like to build a dictionary in python in which different keys refer to the same element. 我想在python中构建一个字典,其中不同的键引用相同的元素。 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? 键指的是一个相同的字符串,但字符串在程序中有不同的内存位置,我想制作一个字典,其中所有这些键引用相同的元素,这可能吗?

You could do something like: 你可以这样做:

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

This transforms your dictionary into a dictionary where equal values of any kind(but comparable) are unique. 这会将您的字典转换为字典,其中任何类型的相同值(但可比较)都是唯一的。 If your values are not comparable(but are hashable) you could use a temporary dict : 如果您的值不具有可比性(但可以清除),您可以使用临时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)))

If you happen to be using python 3, sys.intern offers a very elegant solution: 如果你碰巧使用python 3, sys.intern提供了一个非常优雅的解决方案:

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

In Python 2.7, you can do roughly the same thing with one extra step: 在Python 2.7中,您可以通过一个额外步骤执行大致相同的操作:

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

In 2.x (< 2.7), you can write interned = dict( (v, v) for … ) instead. 在2.x(<2.7)中,您可以编写interned = dict( (v, v) for … )

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

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