从 python 中的字典元组(取自 json 文件)中提取键和值

Extracting key and value from tuple of dictionaries (taken from json file) in python

我有一个 JSON 文件,它是多个字典的元组,我想从其中一些字典中提取键和值。

文件看起来像这样(这只是具有随机键和值的结构的示例):

file = 
[
    {
        "element": {
            "name": "Ana",
            "bio": "xx",
            "type": "female"
        },
        "ID": "1234",
        "status": "STOPPED"
    },
    {
         "element": {
            "name": "Bob",
            "bio": "xy",
            "type": "male"
        },
        "ID": "5678",
        "status": "STOPPED"
    },
    {
         "element": {
            "name": "Chloe",
            "bio": "xx",
            "type": "female"
        },
        "ID": "8912",
        "status": "STOPPED"
      }
]

我想提取所有姓名(Ana、Bob、Chloe)及其 ID,如下所示:

Ana = 1234,
Bob = 5678

等等

无论我已经尝试过什么都会返回属性错误等。我什至不确定如何正确地迭代它以便它需要 nameID 因为他们没有相同的位置(nameelement 字典中)。

我什至尝试将文件转换为列表。

首先,你必须打开这个JSON文件,让json库解析这个文件,从而产生一个加载的字典。有关详细信息,请参阅 Reading JSON from a file?。一旦你有了你的字典,我称之为 users,你可以执行这个字典理解:

import json

# Load the file into a `users` (nested) dictionary
with open("file.json", "r") as f:
    users = json.load(f)

name_to_ids = {
    person["element"]["name"]: person["ID"]
    for person in users
}

输出:

{'Ana': '1234', 'Bob': '5678', 'Chloe': '8912'}

请注意,如果有人姓名重叠,这可能会导致问题!例如:

# I've simply copied this into the .py file for simplicity.
# You'll want to use the JSON parsing method from the Stack Overflow I linked above.
users = [
    {
        "element": {
            "name": "Ana",
            "bio": "xx",
            "type": "female"
        },
        "ID": "1234",
        "status": "STOPPED"
    },
    {
         "element": {
            "name": "Ana",
            "bio": "xy",
            "type": "male"
        },
        "ID": "5678",
        "status": "STOPPED"
    }
]

name_to_ids = {
    person["element"]["name"]: person["ID"]
    for person in users
}

print(name_to_ids)

输出:

{'Ana': '5678'}