[英]Extract JSON Value From Nested List in Python
我正在使用 OMDb API 使用 Python 提取電影/電視節目數據。 我正在嘗試從以下 JSON 獲得 IMDB、爛番茄和 Metacritic 評級。
{
"title": "One Hundred and One Dalmatians",
"year": "1961",
"rated": "G",
"ratings": [
{
"source": "Internet Movie Database",
"value": "7.2/10"
},
{
"source": "Rotten Tomatoes",
"value": "98%"
},
{
"source": "Metacritic",
"value": "83/100"
}
],
"response": "True"
}
我想要 Rotten Tomatoes 源的嵌套評級列表中的“98%”值。 我怎樣才能得到它而不是使用像omdb_media['ratings'][1]['Value']
這樣的東西? 爛番茄並不總是有條目,我也不能保證順序,因為可能沒有 IMDB 或 Metacritic 的條目,但爛番茄有一個條目,因此它的索引會發生變化。
理想情況下,我希望能夠搜索 JSON 並通過搜索“爛番茄”來獲得該值。
這可能嗎? 我會怎么做 go
json ={
"title": "One Hundred and One Dalmatians",
"year": "1961",
"rated": "G",
"ratings": [
{
"source": "Internet Movie Database",
"value": "7.2/10"
},
{
"source": "Rotten Tomatoes",
"value": "98%"
},
{
"source": "Metacritic",
"value": "83/100"
}
],
"response": "True"
}
for rating in json["ratings"] :
if(rating["source"] == "Rotten Tomatoes") :
print(rating["value"])
假設ratings
列表中的每個條目都有一個來源和一個值,並且每個評分都有一個唯一的來源,您可以執行以下操作:
# Generate a new list, with any ratings that aren't from Rotten Tomatoes removed.
rotten_tomatoes_ratings = filter(lambda x: x['source'] == 'Rotten Tomatoes', omdb_media['ratings'])
# Only execute the following code if there exists a rating from Rotten Tomatoes.
if rotten_tomatoes_ratings:
[rating] = rotten_tomatoes_ratings
# Do stuff with rating...
您可以只要求source
為"Rotten Tomatoes"
的next()
評級。 如果源不匹配,最后的None
是結果,這可以是您想要的任何默認值:
source = 'Rotten Tomatoes'
rt = next((rating['value']
for rating in d['ratings']
if rating['source'] == source), None)
print(rt)
# 98%
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.