我有一个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"
}
]
我想提取的所有名字(安娜,鲍勃,克洛伊(和他们的ID类似这样:
Ana=1234,
Bob=5678
等。
无论我已经尝试过什么,都会返回属性错误等。我甚至不知道如何正确地迭代,以便使用name
和ID
,因为它们没有相同的位置(name
在element
dict内(。
我甚至尝试将文件转换为列表。
首先,您必须打开这个JSON文件,并让json
库解析这个文件,从而生成一个加载的字典。请参阅从文件中读取JSON?了解更多信息。一旦你有了字典,我称之为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'}