I want to make a 2d dictionary with multiple keys per value. I do not want to make a tuple a key. But rather make many keys that will return the same value.
I know how to make a 2d dictionary using defaultdict:
from collections import defaultdict
a_dict = defaultdict(dict)
a_dict['canned_food']['spam'] = 'delicious'
And I can make a tuple a key using
a_dict['food','canned_food']['spam'] = 'delicious'
But this does not allow me to do something like
print a_dict['canned_food']['spam']
Because ‘canned_food’ is not a key the tuple [‘food’,’canned_food’] is the key.
I have learned that I can simply set many to same value independently like:
a_dict['food']['spam'] = 'delicious'
a_dict['canned_food']['spam'] = 'delicious'
But this becomes messy with a large number of keys. In the first dimension of dictionary I need ~25 keys per value. Is there a way to write the dictionary so that any key in the tuple will work?
I have asked this question before but was not clear on what I wanted so I am reposting. Thank you in advance for any help.
Here is a possible solution:
Which can be used like so:
Note there are some edge cases with undefined behavior – such as using the same key for multiple aliases. I feel this makes this data type pretty awful for general use, and I’d suggest that you may be better off changing your program not to need this kind of overly convoluted structure instead.
Also note this solution is for 3.x, under 2.x, you will want to swap out
strforbasestring, andself.aliases.keys()forself.aliases.viewkeys().