我正在使用 OMDb API 使用 Python 提取電影/電視節目資料。我正在嘗試從以下 JSON 中獲取 IMDB、Rotten Tomatoes 和 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']?Rotten Tomatoes 并不總是有條目,我也不能保證順序,因為可能沒有 IMDB 或 Metacritic 的條目,但 Rotten Tomatoes 有一個條目,所以它的索引會發生變化。
理想情況下,我希望能夠搜索 JSON 并通過能夠搜索“爛番茄”來獲得該值。
這可能嗎?我將如何去做?
uj5u.com熱心網友回復:
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"])
uj5u.com熱心網友回復:
假設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...
uj5u.com熱心網友回復:
你可以只要求next()在sourceis的評級"Rotten Tomatoes"。None如果源不匹配,則最后是結果,這可以是您想要的任何默認值:
source = 'Rotten Tomatoes'
rt = next((rating['value']
for rating in d['ratings']
if rating['source'] == source), None)
print(rt)
# 98%
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/395918.html
