Finding scores from a list

BartC bc at freeuk.com
Tue Nov 24 09:12:39 EST 2015


On 24/11/2015 13:25, Cai Gengyang wrote:
>
> results = [
> {"id": 1, "name": "ensheng", "score": 10},
> {"id": 2, "name": "gengyang", "score": 12},
> {"id": 3, "name": "jordan", "score": 5},
> ]
>
> I want to find gengyang's score. This is what I tried :
>
>>>> print((results["gengyang"])["score"])
>
> but I got an error message instead :
>
> Traceback (most recent call last):
>    File "<pyshell#62>", line 1, in <module>
>      print((results["gengyang"])["score"])
> TypeError: list indices must be integers, not str
>
> Any ideas how to solve this? Thank you ..

Your new results type is a list of dicts.

Lists are indexed by a number. That will be results[1] for the dict 
relevant to "gengyang" (not even the 2 of the "id", because lists start 
counting at 0).

To find the entry for particular name, you have to search for it (for a 
list entry where the dict key "name" gives you the value you expect, ie. 
"gengyang" in this example).

So a dict of dicts was a better idea.

-- 
Bartc



More information about the Python-list mailing list