I have downloaded a json file and imported it into python as a dict. Now the dict shows that it only has a len of 2 'id' and 'stats'. I would like to extract the values of 'stats' as a separate dict, so I can manipulate the data further. The manipulation which I want to do further is that I only want the first part of 'stats'. Thus I would only have the stats for the player_fullname = 'Lenny Hampel'.
My Questions: 1. How to get the values of 'stats' into a separate dict? 2. How to only get the values of 'player_fullname': 'Lenny Hampel'?
You can get your list of dicts with
dct_lst = lennymatch1["stats"]
And then the player with the name "Lenny Hampel":
player = [item for item in dct_lst if item["player_fullname"] == "Lenny Hampel"]
All in one go
player = [item
for item in lennymatch1["stats"]
if item["player_fullname"] == "Lenny Hampel"]
stats is a list of dicts not a dict. to get the list as a separate variable simply:
stats = data['stats']
To extract all the names use a list comprehension:
names = [d['player_fullname' ] for d in data['stats']]
And to get a specific dict in that list use:
lennymatch = next(d for d in data if d['player_fullname'] == "Lenny Hampel")
This will raise an error if the name isn't in the list/dicts if you want it to return an empty dict then use the default parameter of next or try/except it depending on your needs
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.