【问题标题】:Create automatically list in a nested dictionary python在嵌套字典python中自动创建列表
【发布时间】:2023-01-27 20:41:29
【问题描述】:

我从一个大数据框中提取带有标签和值的列表,我将它们存储到两个单独的列表中,例如:

[['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], [114.98, 17.4, 21.1, 7.99, 51.5, 3000.0, 7.99, 68.5, 19.99]]

在我想每个月都将这个标签和值列表存储在内部之后,在我想将所有 12 个月(我使用 1 到 12 的数字存储到代码中)存储到年份字典中之后

我想创建一个以这种方式格式化的字典:

{
2018.0: {1: [['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], [114.98, 17.4, 21.1, 7.99, 51.5, 3000.0, 7.99, 68.5, 19.99]], 2: [['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], [114.98, 17.4, 21.1, 7.99, 51.5, 3000.0, 7.99, 68.5, 19.99]], 3: [['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], [114.98, 17.4, 21.1, 7.99, 51.5, 3000.0, 7.99, 68.5, 19.99]], 4: [['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], [114.98, 17.4, 21.1, 7.99, 51.5, 3000.0, 7.99, 68.5, 19.99]],
2019.0: {1: [['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], [114.98, 17.4, 21.1, 7.99, 51.5, 3000.0, 7.99, 68.5, 19.99]], 2: [['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], [114.98, 17.4, 21.1, 7.99, 51.5, 3000.0, 7.99, 68.5, 19.99]], 3: [['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], [114.98, 17.4, 21.1, 7.99, 51.5, 3000.0, 7.99, 68.5, 19.99]], 4: [['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], [114.98, 17.4, 21.1, 7.99, 51.5, 3000.0, 7.99, 68.5, 19.99]]
...
}

我的代码的问题在于它存储了所有年份中所有月份的相同标签和值。正如您从一段代码中看到的那样,我只审查了标签,但在代码中所有月份的标签和值都是相等的,而且是不正确的。 我知道这有点令人困惑。我的东西没有很好地解释让我知道。

我试过这个: 这一种变量来自另一个迭代年份的 For 循环,并且是为了

dma=dict.fromkeys(list_years) #how it looks dma {2018.0: None, 2019.0: None, 2020.0: None, 2021.0: None, 2022.0: None}
med=dict.fromkeys(list_months) #how it looks med {1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None, 10: None, 11: None, 12: None}

for argomento in lista_cat_pulita:
            new_df = df.loc[(df["tipo"]=="Expense") & (df["mese"]==m) & (df["anno"]==a) & (df["categoria"]==argomento), "somma"].sum()

        label.append(argomento)
                value.append(new_df)

insieme.append(label)
insieme.append(value)

for ke, ve in dma.items():
    if ke == a:
        dma[ke]= med
        for ki, vi in med.items():
            if ki == m:
                med[ki] = insieme

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    你想创建一个字典的字典。利用:

    ml = [['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], [114.98, 17.4, 21.1, 7.99, 51.5, 3000.0, 7.99, 68.5, 19.99]]
    
    years = ['2001.0', '2002.0']
    
    main_dict = {}
    for year in years:
        main_dict[year] =  {i: ml for i in range(1,5)}
    
    print(main_dict)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      相关资源
      最近更新 更多