Sum nested key values of dict
问题 This is my sample dictionary in Python 2.7: sample = {'T1': {'P1': 20, 'P2': 100}, 'T2': {'P1': 60, 'P2': 50}} I am trying to sum up all the values with the key 'P1' and 'P2' to get a result like this: reqResult = [80,150] How would I go about this? Many thanks. 回答1: You can use >>> d = {'T1': {'P1': 20, 'P2': 100}, 'T2': {'P1': 60, 'P2': 50}} >>> map(sum, zip(*[x.values() for x in d.values()])) [150, 80] This will first compute the innner dicts, than take out their values and zip them