Anake
Anake

Reputation: 7659

python dictionary- two keys to each value

Hi I am fairly sure you can't do this but I was wondering if you could have a dictionary where each of the values can be accessed via two keys without duplicating the dictionary.

The reason I want to do this is that the two keys will represent the same thing but one will be a shortened version eg. 'TYR' and 'Y' will both have the same value.

Upvotes: 4

Views: 2149

Answers (1)

rplnt
rplnt

Reputation: 2409

Just place same (mutable) object in two places. If you change the object it will change in both places in the dictionary. Only donwside is that you have to add and delete both explicitly (you could create some helper method though).

In [4]: d = {}
In [5]: c = [1,2]
In [7]: d[1] = c
In [8]: d[2] = c
In [9]: d
Out[9]: {1: [1, 2], 2: [1, 2]}
In [10]: c.append(3)
In [11]: d
Out[11]: {1: [1, 2, 3], 2: [1, 2, 3]}

If you want to store unmutable types like string and tuple, you probably need to create object that will store in them and change it inside that object.

Upvotes: 5

Related Questions