Finding scores from a list

John Gordon gordon at panix.com
Tue Nov 24 12:47:17 EST 2015


In <277843f7-c898-4378-85ea-841b09a289e3 at googlegroups.com> Cai Gengyang <gengyangcai at gmail.com> writes:


> results = [
> {"id": 1, "name": "ensheng", "score": 10},
> {"id": 2, "name": "gengyang", "score": 12},
> {"id": 3, "name": "jordan", "score": 5},
> ]

Okay, this is a list.

> 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

Lists are indexed by number, not by name.

You want something like this:

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

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon at panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"




More information about the Python-list mailing list