Can I use multiple keys in a python dictionary?

I would like to build a dictionary in python in which different keys belong to the same element. I have this dictionary:

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

the key refers to the same line, but the lines have a different memory cell inside the program, I would like to make a dictionary in which all these keys belong to the same element, is this possible?

+5
source share
2 answers

You can 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 turns your dictionary into a dictionary where the same values ​​of any type (but comparable) are unique. If your values ​​are not comparable (but hashed), you can use a temporary 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)))
+5
source

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]]

2.x(< 2.7) interned = dict( (v, v) for … ) .

+1

All Articles