我需要一个简单的嵌套字典包装器,我尝试了类似这样的东西
class DictWrapper(object):
def __init__(self, x_names, y_names):
self._dict = {}
for x in x_names:
self._dict[x] = {}
for y in y_names:
self._dict[x][y] = {}
def __setitem__(self, x, y, val):
self._dict[x][y] = val
def __getitem__(self, x, y):
return self._dict[x][y]
if __name__ == '__main__':
results_holder = DictWrapper(['x1', 'x2', 'x3'], ['y1', 'y2'])
results_holder['x1']['y2'] = 11
然而,这导致以下错误:
results_holder['x1']['y2'] = 11
TypeError: __getitem__() takes exactly 3 arguments (2 given)
我是否在正确的轨道上?如何使这种简单的字典包装工作?
答案 0 :(得分:-1)
Python字典已经可以嵌套了。
您已经可以使用itertools.product
:
from itertools import product
x = ['x1', 'x2', 'x3']
y = ['y1', 'y2']
results_holder = dict( # transform to dict
product( # build the matrice
x, [dict(product(y, [{}]))]
))
results_holder['x1']['y2'] = 11