我试图在另一个嵌套字典中生成一个嵌套字典,但是我只能完成一个步骤。
这是我得到的代码:
variables = ['CHG', 'Open', 'Close']
assets= ['GOOG', 'FB']
dates =['28-09-2020', '25-09-2020']
dct = {x: dict(zip(assets, '0' * len(assets))) for x in dates}
得到我:
{'28-09-2020': {'GOOG': '0', 'FB': '0'}, '25-09-2020': {'GOOG': '0', 'FB': '0'}}
如何在每个资产中包含变量的情况下生成字典?
我的目标是得到这样的命令:
{'28-09-2020': {'GOOG': {'CHG':0, 'Open':0, 'Close':0}, 'FB': {'CHG':0, 'Open':0, 'Close':0}}, '25-09-2020': {'GOOG': {'CHG':0, 'Open':0, 'Close':0}, 'FB': {'CHG':0, 'Open':0, 'Close':0}}}
答案 0 :(得分:2)
{date: {x: dict(zip(variables, '0' * len(variables))) for x in assets} for date in dates}
输出
{'28-09-2020': {'GOOG': {'CHG': '0', 'Open': '0', 'Close': '0'},
'FB': {'CHG': '0', 'Open': '0', 'Close': '0'}},
'25-09-2020': {'GOOG': {'CHG': '0', 'Open': '0', 'Close': '0'},
'FB': {'CHG': '0', 'Open': '0', 'Close': '0'}}}
答案 1 :(得分:0)
让我们从内而外地进行这项工作。
>>> from itertools import repeat
>>> dict.fromkeys(variables, 0)
{'CHG': 0, 'Open': 0, 'Close': 0}
>>> dict(zip(assets, repeat(_)))
{'GOOG': {'CHG': 0, 'Open': 0, 'Close': 0}, 'FB': {'CHG': 0, 'Open': 0, 'Close': 0}}
>>> dict(zip(dates, repeat(_)))
{'28-09-2020': {'GOOG': {'CHG': 0, 'Open': 0, 'Close': 0}, 'FB': {'CHG': 0, 'Open': 0, 'Close': 0}}, '25-09-2020': {'GOOG': {'CHG': 0, 'Open': 0, 'Close': 0}, 'FB': {'CHG': 0, 'Open': 0, 'Close': 0}}}
因此您可以使用
dct = dict(zip(dates, repeat(dict(zip(assets, repeat(dict.fromkeys(variables, 0)))))))
或dict理解形式
dct = {d: {a: dict.fromkeys(variables, 0) for a in assets} for d in dates}
答案 2 :(得分:0)
{d: {a: {v:0 for v in variables} for a in assets} for d in dates}
输出
{'28-09-2020': {'GOOG': {'CHG': 0, 'Open': 0, 'Close': 0}, 'FB': {'CHG': 0, 'Open': 0, 'Close': 0}},
'25-09-2020': {'GOOG': {'CHG': 0, 'Open': 0, 'Close': 0}, 'FB': {'CHG': 0, 'Open': 0, 'Close': 0}}}