我想解析JSON文件并从JSON获取两个字段并将它们放在字典中。例如:
{
"food": [{
"name": "pasta",
"type": "blabla",
"sauce": [{
"name": "cream",
"url": "http://www...."
}
]
}, {
"name": "pizza",
"type": "bla",
"sauce": [{
"name": "Tomato",
"url": "http://www...."
}
]
}
]
}
我想得到:
{pasta: cream, pizza: Tomato}
答案 0 :(得分:2)
dict comprehension
可以胜任:
data = {
"food": [{
"name": "pasta",
"type": "blabla",
"sauce": [{
"name": "cream",
"url": "http://www...."
}
]
}, {
"name": "pizza",
"type": "bla",
"sauce": [{
"name": "Tomato",
"url": "http://www...."
}
]
}
]
}
foods = data['food']
print( {food['name']:food['sauce'][0]['name'] for food in foods})