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?
You could do something like:
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
:If you happen to be using python 3,
sys.intern
offers a very elegant solution:In Python 2.7, you can do roughly the same thing with one extra step:
In 2.x (< 2.7), you can write
interned = dict( (v, v) for … )
instead.