I think I want to make a 2D dictionary with multiple keys per value.
I know how to make a 2D dictionary using defaultdict:
from collections import defaultdict
2d_dict = defaultdict(dict)
2d_dict['canned_food']['spam'] = 'delicious'
And I know that using regular dictionaries you can make with multiple keys like:
dictionary={('food','canned_food'):spam}
But I want to do something like lookup by tuple-of-keys:
2d_dict[('canned_food','food')]['spam'] = 'delicious'
In the first dimension of dictionary I need ~25 keys per value. Is there a way to do this with defaultdict?
Even if there is a way to do it with dicts is this a reasonable way to make a simple multidimensional lookup table?
Apart from
2d_dictbeing an invalid variable name (it starts with a digit), your existing solution already works:In fact, you don’t even need the parentheses – Python will still recognise your key as a tuple:
… and, yes, it’s a perfectly reasonable way to build a 2D+1D lookup table.
If you want to build a 3D lookup table using nested dicts instead of tuple keys, this works: