如何从一个字典中的一个字典中创建一个具有不同和相似键的字典

2024-09-28 21:53:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典,它有两个键值,每个键值都指向一个本身就是字典的值。现在我关心的是提取值的键值,而不管它们的第一个键是什么。这两个值的键既相同又不同。你知道吗

我需要得到一个单独的字典,其中不同的键保持相同,而两个字典中的键相同,因此有值更新,即它们相加。你知道吗

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'。你知道吗


Tags: jsondata字典withfile键值指向关心
1条回答
网友
1楼 · 发布于 2024-09-28 21:53:03

你可以用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))}

资源:

{'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}

相关问题 更多 >