如何用一些不同且相似的键从词典中的词典中创建单个词典

时间:2019-06-21 22:20:44

标签: python list dictionary

我有一个具有两个键值的字典,每个键都引用一个本身就是字典的值。现在,我关心的是提取值的键值,而不管它们的第一个键如何。这两个值具有相同或不同的键。

我需要得到一个字典,其中不同的键保持相同,而两个字典中的键相同,因此需要进行值更新,即它们加起来。

with open('report.json') as json_file:
    data = json.load(json_file)
    print(data['behavior']['apistats'])

输出包含以下内容:

{
    "2740": {
        "NtDuplicateObject": 2,
        "NtOpenSection": 1,
        "GetSystemWindowsDirectoryW": 23,
        "NtQueryValueKey": 32,
        "NtClose": 427,
        "NtOpenMutant": 2,
        "RegCloseKey": 8
    },
    "3908": {
        "RegCreateKeyExW": 2,
        "GetNativeSystemInfo": 1,
        "NtOpenSection": 1,
        "CoUninitialize": 6,
        "RegCloseKey": 27,
        "GetSystemInfo": 1,
        "CreateToolhelp32Snapshot": 180,
        "UnhookWindowsHookEx": 2,
        "GetSystemWindowsDirectoryW": 6,
        "NtQueryValueKey": 6,
        "NtClose": 427
    }
}

但是我需要一个字典,其中相同的'apistats'值将作为一个新值加起来,并且这些键不会重复,而与父键'2740''3908'无关。

1 个答案:

答案 0 :(得分:0)

您可以使用groupby解决此问题:

input_dict = {
    "2740": {
        "NtDuplicateObject": 2,
        "NtOpenSection": 1,
        "GetSystemWindowsDirectoryW": 23,
        "NtQueryValueKey": 32,
        "NtClose": 427,
        "NtOpenMutant": 2,
        "RegCloseKey": 8,
    },
    "3908": {
        "RegCreateKeyExW": 2,
        "GetNativeSystemInfo": 1,
        "NtOpenSection": 1,
        "CoUninitialize": 6,
        "RegCloseKey": 27,
        "GetSystemInfo": 1,
        "CreateToolhelp32Snapshot": 180,
        "UnhookWindowsHookEx": 2,
        "GetSystemWindowsDirectoryW": 6,
        "NtQueryValueKey": 6,
        "NtClose": 427,
    },
}

from itertools import groupby
from operator import itemgetter

refactored_items = ((k2, v2) for v1 in input_dict.values() for k2, v2 in v1.items())
sorted_refactored_items = sorted(refactored_items, key=itemgetter(0))
res = {k: sum(i for _, i in g) for k, g in groupby(sorted_refactored_items, key=itemgetter(0))}

res:

{'CoUninitialize': 6,
 'CreateToolhelp32Snapshot': 180,
 'GetNativeSystemInfo': 1,
 'GetSystemInfo': 1,
 'GetSystemWindowsDirectoryW': 29,
 'NtClose': 854,
 'NtDuplicateObject': 2,
 'NtOpenMutant': 2,
 'NtOpenSection': 2,
 'NtQueryValueKey': 38,
 'RegCloseKey': 35,
 'RegCreateKeyExW': 2,
 'UnhookWindowsHookEx': 2}