这是我想要的输出:
level1 = {'value1':0, 'value2':0, 'value3':0}
level2 = {'value1':0, 'value2':0, 'value3':0}
level3 = {'value1':0, 'value2':0, 'value3':0}
level3 = {'value1':0, 'value2':0, 'value3':0}
注意:Value1,Value2和Value3都是一样的。我用它来填充词典。
以下是我的尝试:
for x in range (1,6):
level = 'level%d' % x
for iteration in range(1, 4):
value = 'value%d' % iteration
level = {}
level['value'] = 0
答案 0 :(得分:1)
你在尝试这样的事吗?:
dic={}
for x in range (1,6):
level = 'level%d' % x
dic[level] = {}
for iteration in range(1, 4):
value = 'value%d' % iteration
dic[level][value] = 0
print dic
输出:
{'level1': {'value1': 0, 'value2': 0, 'value3': 0},
'level2': {'value1': 0, 'value2': 0, 'value3': 0},
'level3': {'value1': 0, 'value2': 0, 'value3': 0},
'level4': {'value1': 0, 'value2': 0, 'value3': 0},
'level5': {'value1': 0, 'value2': 0, 'value3': 0}}
答案 1 :(得分:1)
所以你想要这样的东西:
keys = ('value1','value2','value3')
{k:dict.fromkeys(keys,0) for k in range(1,4)}
演示:
>>> keys = ('value1','value2','value3')
>>> {k:dict.fromkeys(keys,0) for k in range(1,4)}
{1: {'value3': 0, 'value2': 0, 'value1': 0}, 2: {'value3': 0, 'value2': 0, 'value1': 0}, 3: {'value3': 0, 'value2': 0, 'value1': 0}}
当然,使用顺序整数作为键,您可以考虑从0开始索引并改为使用列表推导:
[dict.fromkeys(keys,0) for _ in range(3)]
答案 2 :(得分:1)
您可以将for
循环嵌套在嵌套的dictionary comprehension中,并创建一个两级嵌套字典,如下所示:
from pprint import pprint
nested_dict = {'level%d' % level:
{'value%d' % value: 0 for value in range(1, 4)}
for level in range(1, 6)}
pprint(nested_dict)
输出:
{'level1': {'value1': 0, 'value2': 0, 'value3': 0},
'level2': {'value1': 0, 'value2': 0, 'value3': 0},
'level3': {'value1': 0, 'value2': 0, 'value3': 0},
'level4': {'value1': 0, 'value2': 0, 'value3': 0},
'level5': {'value1': 0, 'value2': 0, 'value3': 0}}