开发者

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 t开发者_开发技巧hat 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜