How to index into a list of dictionaries?

  • A+
Category:Languages

Newbie alert- but have spent a few hours now on this and just cant figure it out - i have this list :

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'}] 

What i would like to do was to be able to say :

players["John"]["score"]=newScore players["john"]["Played"] = players["john"]["Played"]+1 

This list represents like a list of objects, where the name is the primary key and then theres parameters for each object.

But ofcourse that doesnt work, im able to touch elements by, ex doing :

print (players[0]["score"]) 

and this would then print Johns score alright, but with this way i would need to go through all players[x] to first compare if the name is the same, and then i can access it, it just doesnt seems so python to me.

How would you go about this in a pythonic way ?


You could wrap your current data with a class that could provide the specialized update methods you specified, without changing the entire structure of your original data to begin with:

class Row:    def __init__(self, row):       self.row = row    def __setitem__(self, _t, _val):       self.row[_t] = str(_val)    def __getitem__(self, _stat):       return int(self.row[_stat])    def __repr__(self):       return '{}({})'.format(self.__class__.__name__, str(self.row))  class Players:    def __init__(self, data={}):       self.data = {i['name']:Row(i) for i in data}    def __getitem__(self, name):       return self.data[name]    def __setitem__(self, _name, _data):       self.data[_name] = Row(_data)    def __repr__(self):       return '{}({})'.format(self.__class__.__name__, str(self.data))  players = [{'points': '27', 'name': 'John', 'Played': '6'}, {'points': '43', 'name': 'Emil', 'Played': '13'}, {'points': '11', 'name': 'Susan', 'Played': '2'}, {'points': '4', 'name': 'Peter', 'Played': '3'}] d = Players(players) d['John']['points'] = 30 d["John"]["Played"] = d["John"]["Played"]+1 print(d['John']) d['Bob'] = {'points': '2', 'Played': '5'} 

Output:

Row({'points': '30', 'name': 'John', 'Played': '7'}) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: