将2d dict内的值除以与该键匹配的另一个dict值

时间:2018-09-04 20:18:52

标签: python python-3.x dictionary

这些字典很长,我需要遍历多个键值。 举一个简短的例子。从长远来看,我需要将所有数字除以适当的计数以获得平均值。

counts = {'A':10, 'B':14}
totals = {'A':{'atk':20,'str':20,'def':20}, 
          'B':{'atk':140,'str':140,'def':140}}

我需要更新总数,以便最终

totals = {'A':{'atk':2,'str':2,'def':2}, 
          'B'{'atk':10, 'str':10,'def':10}}

1 个答案:

答案 0 :(得分:1)

我将使用O(1)字典查找

>>> {k1: {k2: v/counts[k1]  for k2, v in d.items()} for k1, d in totals.items() }

{'A': {'atk': 2.0, 'str': 2.0, 'def': 2.0},
 'B': {'atk': 10.0, 'str': 10.0, 'def': 10.0}}

可以随时扩展理解范围。

f = {}
for k1, d in totals.items():
    sub = {}
    for k2, v in d.items():
        sub[k2] = v/counts[k1]
    f[k1] = sub