Finding scores from a list

Peter Otten __peter__ at web.de
Tue Nov 24 08:50:01 EST 2015


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 ..

As the outer container is a list you have to provide an index:

results[1]["score"]

You can also search for a matching item:

for result in results:
   if result["name"] == "gengyang":
       print(result["score"])

but when the list grows performance will suffer.

General note: you will have a better experience learning Python when you 
read some introductory text first, to get the big picture.




More information about the Python-list mailing list