如何索引到词典列表?

MdT*_*dTp 3 python dictionary python-3.x

新手警报 - 但现在已经花了几个小时在这个,只是无法搞清楚 - 我有这个清单:

players = [{'name': 'John', 'points': '27', 'Played': '6'},
{'name': 'Emil', 'points': '43', 'Played' : '13'},
{'name': 'Susan', 'points': '11', 'Played': '2'},
{'name': 'Peter', 'points': '4', 'Played': '3'}]
Run Code Online (Sandbox Code Playgroud)

我想做的是能够说:

players["John"]["score"]=newScore
players["john"]["Played"] = players["john"]["Played"]+1
Run Code Online (Sandbox Code Playgroud)

此列表表示对象列表,其中名称是主键,然后是每个对象的theres参数.

但是当然不起作用,我能够通过以下方式触摸元素:

print (players[0]["score"])
Run Code Online (Sandbox Code Playgroud)

然后这将打印出Johns得分好,但是通过这种方式,我需要通过所有玩家[x]首先比较一下,如果名字是相同的,然后我可以访问它,它对我来说似乎不是那么蟒蛇.

你会怎样以pythonic方式进行此操作?

ACh*_*ion 7

更改您的数据结构,如果Name是关键,则只需:

players_dict = {d['Name']: d for d in players}
Run Code Online (Sandbox Code Playgroud)

会允许你这样做:

players_dict["John"]["score"] = new_score
Run Code Online (Sandbox Code Playgroud)