【问题标题】:Adding sum of the nested dictionary values using keys from the list使用列表中的键添加嵌套字典值的总和
【发布时间】:2022-01-21 18:58:10
【问题描述】:

我正在创建一个战争游戏,我有这本武器词典以及它们对另一种部队造成的伤害。

另外,我有一个列表,其中存储了字典中的键。

weapon_specs = {
 'rifle': {'air': 1, 'ground': 2, 'human': 5},
 'pistol': {'air': 0, 'ground': 1, 'human': 3},
 'rpg': {'air': 5, 'ground': 5, 'human': 3},
 'warhead': {'air': 10, 'ground': 10, 'human': 10},
 'machine gun': {'air': 3, 'ground': 3, 'human': 10}
}

inv = ['rifle', 'machine gun', 'pistol'] 

我需要得到这个输出:

{'air': 4, 'ground': 6, 'human': 18}

我试过了:

for i in weapon_specs:
  for k in inv:
    if i == k:
        list.update(weapon_specs[k])

【问题讨论】:

    标签: python list loops dictionary for-loop


    【解决方案1】:

    你可以使用collections.Counter:

    from collections import Counter
    count = Counter()
    for counter in [weapon_specs[weapon] for weapon in inv]:
        count += counter
    out = dict(count)
    

    如果你不想使用collections库,你也可以这样做:

    out = {}
    for weapon in inv:
        for k,v in weapon_specs[weapon].items():
            out[k] = out.get(k, 0) + v
    

    输出:

    {'air': 4, 'ground': 6, 'human': 18}
    

    【讨论】:

      【解决方案2】:

      无需导入任何东西。你可以用两个循环来映射字典。

      out = {'air': 0, 'ground': 0, 'human': 0}
      
      for weapon in inv:
          for k, v in weapon_specs[weapon].items():
              out[k] += v
      
      print(out)
      

      输出:

      {'air': 4, 'ground': 6, 'human': 18}
      

      【讨论】:

        【解决方案3】:

        使用集合中的计数器参考 inv 添加字典值

        from collections import Counter
        weapon_specs = {'rifle': {'air': 1, 'ground': 2, 'human': 5},'pistol': {'air': 0, 'ground': 1, 'human': 3},'rpg': {'air': 5, 'ground': 5, 'human': 3},'warhead': {'air': 10, 'ground': 10, 'human': 10},'machine gun': {'air': 3, 'ground': 3, 'human': 10}}
        inv = ['riffle', 'machine gun', 'pistol']
        summation = Counter()
        for category, values in weapon_specs.items():
            if category in inv:
                summation.update(values)
        summation = dict(summation)
        print(summation)
        

        输出:

        {'air': 4, 'ground': 6, 'human': 18}
        

        【讨论】:

          【解决方案4】:

          首先根据您的列表获取字典的子集。
          然后使用Counter

          from collections import Counter
          subset = {k: weapon_specs[k] for k in inv}
          out = dict(sum((Counter(d) for d in subset.values()), Counter()))
          

          结果

          {'air': 4, 'ground': 6, 'human': 18}
          

          【讨论】:

            猜你喜欢
            • 2020-09-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-04-02
            • 1970-01-01
            • 2021-05-17
            • 1970-01-01
            • 2015-09-19
            相关资源
            最近更新 更多