[英]How do you call a value in a list within a json dictionary
I'm using api's to call movie reviews in the format 'title': [rating, review]. 我正在使用api以“标题”格式调用电影评论:[评分,评论]。 After using a json.loads() function the json list looks something like this: 使用json.loads()函数后,json列表如下所示:
listResult: {'Shawsank Redemption': [10, 'I love this movie so much'], 'Tropic Thunder': [9,'This was an awesome movie for sure'], 'Ted': [8, 'Hilarious throughout the entire movie']}
I have to return the highest rated movie, I'm assuming I have to use a for loop to find the max value but I'm unsure how to access just the rating value within the list 我必须返回收视率最高的电影,假设我必须使用for循环来查找最大值,但是我不确定如何仅访问列表中的收视率值
Assuming your dictionary has the name listResult
(which you should change, it's not a list), use the built in max
function and provide a custom key-function: 假设您的字典名称为listResult
(您应该更改它,而不是列表),请使用内置的max
函数并提供一个自定义键函数:
>>> listResult = {'Shawsank Redemption': [10, 'I love this movie so much'], 'Tropic Thunder': [9,'This was an awesome movie for sure'], 'Ted': [8, 'Hilarious throughout the entire movie']}
>>> max(listResult, key=lambda movie: listResult[movie][0])
'Shawsank Redemption'
The keyfunction is used to define the criteria by which the movie-names are ordered. 键功能用于定义影片名称排序的标准。 For each movie, we're getting the first element of the corresponding list. 对于每部电影,我们都获得了相应列表的第一个元素。
Here is how to access the rating part of the python list. 这是访问python列表的评价部分的方法。
listResult = {'Movie': [10, "I love this Movie"]}
rating = listResult["Movie"][0]
print rating // Prints 10
Then just compare each of the ratings to find the max one. 然后只需比较每个评级即可找到最大评级。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.