Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 756
FEderico SOmaschini Avatar asked Apr 21 '13 08:04

FEderico SOmaschini


1 Answers

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:

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)))
like image 84
Bakuriu Avatar answered Sep 29 '22 18:09

Bakuriu