如何将值添加到嵌套字典?

时间:2020-06-23 23:27:27

标签: python dictionary nested

我有国家清单

states = ['Arizona','New York']  

和另一个日期列表

dates = ['2020-04-05','2020-01-02','2020-03-28']

我的编程正在根据状态和每个日期输出一些值。我想要最终的输出以嵌套字典的形式

out = {'Arizona': {'2020-04-05':15, '2020-01-02':30, '2020-03-28':50}, 'New York': {'2020-04-05':15, '2020-01-02':100, '2020-03-28':75}}

值15、30、50、100、75是从代码生成的输出。

注意:输出值是从数据框中提取的,状态和日期的数量将根据用户的选择而变化

1 个答案:

答案 0 :(得分:0)

dates = ['2020-04-05','2020-01-02','2020-03-28']
states = ['Arizona','New York']  
out = dict()
    
for s in states:
    out[s] = dict()
    for d in dates:
        out[s][d] = 0    # put your corresponding output here instead of 0

print(out)

输出:

{'Arizona': {'2020-04-05': 0, '2020-01-02': 0, '2020-03-28': 0}, 'New York': {'2020-04-05': 0, '2020-01-02': 0, '2020-03-28': 0}}
  1. 创建外部词典。
  2. 然后遍历各个州,为每个州创建一个新的词典。
  3. 然后迭代日期,将日期作为键,并输入每个日期的值。