如何获取具有相同名称的所有键并将它们放在Python中的单独字典中

时间:2017-05-19 00:24:11

标签: python dictionary

我们说我有一本庞大的价值词典。 (这是值。请注意格式it's not detailed)

无论如何,有多个具有相同名称的键,但它们位于不同的位置。我真正需要的是从所述密钥获取值并将它们加在一起:例如totalSessionsLost和totalSessionsWon

2 个答案:

答案 0 :(得分:1)

这是一种方法:

subdicts = huge_dict_of_values['champions']
keys = subdicts[0]['stats'].keys() # assuming that no dict has keys that this one doesn't have, for simplicity 
totals = {key: sum([subdict['stats'][key] for subdict in subdicts] for key in keys])}

输出:

>>> totals
{'totalPhysicalDamageDealt': 16313032, 'totalTurretsKilled': 316, 'totalSessionsPlayed': 254, 'totalAssists': 2208, 'totalDamageDealt': 31926510, 'totalQuadraKills': 2, 'totalPentaKills': 0, 'mostSpellsCast': 0, 'totalDoubleKills': 178, 'maxChampionsKilled': 450, 'totalDeathsPerSession': 1842, 'totalSessionsWon': 132, 'totalGoldEarned': 3064958, 'totalTripleKills': 26, 'totalChampionKills': 1730, 'maxNumDeaths': 485, 'totalMinionKills': 36376, 'totalMagicDamageDealt': 12982770, 'mostChampionKillsPerSession': 450, 'totalUnrealKills': 0, 'totalDamageTaken': 5812772, 'totalSessionsLost': 122, 'totalFirstBlood': 0}
>>> 

一般来说,当你有这样的嵌套字典时,你可能会更好地使用面向对象的表示。看起来这里有几层语义,如果要给它们命名并更明确地定义它们的关系,那么处理它们要容易得多

这也允许您在每一层编写代码来处理这种报告,这种报告更容易阅读,测试和维护

答案 1 :(得分:1)

以下是一个解决方案的示例,该解决方案可以读取您的j.json文件并返回dict,其中包含文件集内所有键的总和:

<强> PS:

这种代码可以用这种格式对文件的数据求和:

{...,key1:[{..., key2:{...keys_of_elements_to_sum...}}, {..., key3:{...keys_of_elements_to_sum...}}, ...]}

所以,这是代码:

from ast import literal_eval
from itertools import groupby

def get_sum_of_repeated_keys(data):
    keys = []
    for k in data:
        # check the key is a list
        if isinstance(data[k], list):
            # if the key is a list
            # We'll parse all the list's elements
            for j in data[k]:
                # if the elements of the previous list
                # are dicts
                if isinstance(j, dict):
                    # parse the keys of the list's dicts
                    for m in j:
                        # If the elements of the previous list's dicts are dicts
                        if isinstance(j[m], dict):
                            # Appends the items to the list called keys
                            keys += j[m].items()

    # return a dict with the sum of the groupped elements by key
    return {k:sum(k[1] for k in list(v)) for k, v in groupby(sorted(keys), lambda x: x[0])}

# Read the JSON file and convert it into a python dict
with open('j.json', 'r') as f:
    a = f.read().rstrip("\n")
    # This code uses 'literal_eval'
    # because your input file isn't a valid JSON file
    data = literal_eval(a)

# The final result
final = get_sum_of_repeated_keys(data)
# list the keys of the final result
# print(final.keys())
# Print an elements using its key
print("Total sessions won:", final['totalSessionsWon'])
print("Total sessions lost:", final['totalSessionsLost'])

输出:

Total sessions won: 132
Total sessions lost: 122