【问题标题】:Mean values over nested dictionary of dictionary字典嵌套字典的平均值
【发布时间】:2023-04-03 02:36:01
【问题描述】:

我在 Python 中有以下嵌套字典:

     {'data1':{'IOU':{'B':0.1,'G':0.3},
              'lines':{'B':{'accuracy':0.3, "recall":0.3},'G':{'accuracy':0.1, "recall":0.6}}},
      'data2':{'IOU':{'B':0.2,'G':0.8},
              'lines':{'B':{'accuracy':0.5, "recall":0.3},'G':{'accuracy':0.9, "recall":0.5}}}}

从这里我想创建一个像这样的新字典:

{'lines':{'B':{'accuracy':0.4, 'recall': 0.3}, 'G':{'accuracy':0.5, "recall":0.55}}}}

我基本上想为'lines'键获取一个嵌套字典,这样:

  • 新键是 B 和 G
  • 新值是每个键(B 和 G)和每个指标(准确度和召回率)的平均值

我正在为此苦苦挣扎,有人可以建议如何编写代码吗?

【问题讨论】:

  • 你已经尝试了什么,你还停留在哪一部分?

标签: python dictionary nested


【解决方案1】:

您可以在输入字典上使用 dict 理解(我们称之为 d_in):

letters = ["B", "G"]
metrics = ["accuracy", "recall"]

result = {
    "lines": {
        letter: {
            metric: (
                sum(data["lines"][letter][metric] for data in d_in.values()) / len(d_in)
            )
            for metric in metrics
        }
        for letter in letters
    }
}

【讨论】:

  • 非常感谢!这非常有用,使用 dict 理解对我来说更容易理解。
猜你喜欢
  • 2023-03-15
  • 2020-08-20
  • 2021-12-24
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
相关资源
最近更新 更多