使用Python将json重新格式化为键值对

7d7tgy0s  于 2022-11-19  发布在  Python
关注(0)|答案(1)|浏览(190)

我有一个JSON文件,看起来像下面:

{"Africa":
    {
        "invitee_event_type_page":
        {
            "Total Events": "194"
        },
        "invitee_meeting_cancelled":
        {
            "Total Events": "9"
        }
    },
    "Asia":
    {
        "invitee_event_type_page":
        {
            "Total Events": "127"
        },
        "invitee_meeting_scheduled":
        {
            "Total Events": "16"
        }
    }
}

我试图格式化这一点,使我的东西沿着下面的路线:

output = [{"Asia - invitee_event_type_page": 127, "Asia - invitee_meeting_scheduled":16, "Africa - invitee_event_type_page": 194,"Africa - invitee_meeting_cancelled":9}]

我尝试了以下几个问题,但我的运气不太好。我对这一切都很陌生,我正在努力将其他答案的不同部分拼凑成一个连贯的东西。任何帮助都将不胜感激。

import re
import json

with open("ga2.json", "r") as f:
    data =json.load(f)

africa = (data)["Africa"]
output=[]

for key,value in africa.items():
    print(key,value["Total Events"])
    output= output+key,value["Total Events"]
print(output)

我得到TypeError:只能将list(而不是“string”)连接到list。

4szc88ey

4szc88ey1#

您可以使用dict-comprehension来获取您的output

dct = {
    "Africa": {
        "invitee_event_type_page": {"Total Events": "194"},
        "invitee_meeting_cancelled": {"Total Events": "9"},
    },
    "Asia": {
        "invitee_event_type_page": {"Total Events": "127"},
        "invitee_meeting_scheduled": {"Total Events": "16"},
    },
}

out = [
    {
        f"{k} - {kk}": int(vv["Total Events"])
        for k, v in dct.items()
        for kk, vv in v.items()
    }
]

print(out)

印刷品:

[
    {
        "Africa - invitee_event_type_page": 194,
        "Africa - invitee_meeting_cancelled": 9,
        "Asia - invitee_event_type_page": 127,
        "Asia - invitee_meeting_scheduled": 16,
    }
]

相关问题