创建和查找每个值具有多个键的2D词典 [英] Create and lookup 2D dictionary with multiple keys per value
问题描述
我想我要制作一个二维字典,每个值有多个键.
I think I want to make a 2D dictionary with multiple keys per value.
我知道如何使用defaultdict
制作2D词典:
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'
在字典的第一个维度中,每个值需要25个键.有没有办法用defaultdict
做到这一点?
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?
推荐答案
除了2d_dict
是无效的变量名(以数字开头)之外,您现有的解决方案已经有效:
Apart from 2d_dict
being an invalid variable name (it starts with a digit), your existing solution already works:
>>> from collections import defaultdict
>>> d2_dict = defaultdict(dict)
>>> d2_dict[('canned_food', 'food')]['spam'] = 'delicious'
>>> d2_dict
defaultdict(<type 'dict'>, {('canned_food', 'food'): {'spam': 'delicious'}})
实际上,您甚至不需要括号-Python仍会将您的键识别为元组:
In fact, you don't even need the parentheses - Python will still recognise your key as a tuple:
>>> d2_dict['fresh_food', 'food']['eggs'] = 'delicious'
>>> d2_dict
defaultdict(<type 'dict'>, {('canned_food', 'food'): {'spam': 'delicious'},
('fresh_food', 'food'): {'eggs': 'delicious'}})
...,是的,这是构建2D + 1D查找表的一种完全合理的方法.
... and, yes, it's a perfectly reasonable way to build a 2D+1D lookup table.
如果您要使用嵌套字典而不是元组键构建3D查找表,则可以使用该功能:
If you want to build a 3D lookup table using nested dicts instead of tuple keys, this works:
>>> d3_dict = defaultdict(lambda: defaultdict(dict))
>>> d3_dict['dried_food']['food']['jerky'] = 'chewy'
>>> d3_dict
defaultdict(<function <lambda> at 0x7f20af38a2a8>,
{'dried_food': defaultdict(<type 'dict'>, {'food': {'jerky': 'chewy'}})})
这篇关于创建和查找每个值具有多个键的2D词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!