Reputation: 361
I am working with a dictionary from a file with an import. This is the dictionary:
[{'id': 76001,
'full_name': 'Alaa Abdelnaby',
'first_name': 'Alaa',
'last_name': 'Abdelnaby',
'is_active': False},
{'id': 76002,
'full_name': 'Zaid Abdul-Aziz',
'first_name': 'Zaid',
'last_name': 'Abdul-Aziz',
'is_active': False},
{'id': 76003,
'full_name': 'Kareem Abdul-Jabbar',
'first_name': 'Kareem',
'last_name': 'Abdul-Jabbar',
'is_active': False}]
What I want to do is get a list out of all the IDs:
player_ids = [76001,76002, 76003]
I have tried:
player_ids = []
for i in player_dict:
player_ids.append(player_dict[i]['id'])
but I get the error
TypeError: list indices must be integers or slices, not dict
So I get that 'i' is not the place but the actual item I am calling in the dictionary? But I'm not able to make much sense of this based on what I have read.
Upvotes: 0
Views: 97
Reputation: 649
The pythonic way to do this is with a list comprehension. For example:
player_ids = [dict['id'] for dict in player_dict]
This basically loops over all dictionaries in the player_dict, which is actually a list in your case, and for every dictionary gets the item with key 'id'.
Upvotes: 2
Reputation: 27547
Here is how you can use a list comprehension:
player_dict = [{'id': 76001,
'full_name': 'Alaa Abdelnaby',
'first_name': 'Alaa',
'last_name': 'Abdelnaby',
'is_active': False},
{'id': 76002,
'full_name': 'Zaid Abdul-Aziz',
'first_name': 'Zaid',
'last_name': 'Abdul-Aziz',
'is_active': False},
{'id': 76003,
'full_name': 'Kareem Abdul-Jabbar',
'first_name': 'Kareem',
'last_name': 'Abdul-Jabbar',
'is_active': False}]
player_ids = [d['id'] for d in player_dict]
print(player_ids)
Output:
[76001, 76002, 76003]
Upvotes: 1
Reputation: 6056
You can try list comprehension:
>>> [d['id'] for d in my_list]
[76001, 76002, 76003]
Upvotes: 2