0

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.

M--
  • 25,431
  • 8
  • 61
  • 93
elcunyado
  • 351
  • 1
  • 2
  • 11
  • 2
    When you do `for i in player_dict`, `i` is each element in the list not an index. – Mark Jun 24 '20 at 15:38
  • Does this answer your question? [Converting Dictionary to List?](https://stackoverflow.com/questions/1679384/converting-dictionary-to-list) – bad_coder Jun 25 '20 at 01:41

4 Answers4

2

You can try list comprehension:

>>> [d['id'] for d in my_list]
[76001, 76002, 76003]
Asocia
  • 5,935
  • 2
  • 21
  • 46
2

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'.

Bram Dekker
  • 631
  • 1
  • 7
  • 19
  • I get the error 'TypeError: list indices must be integers or slices, not dict' Edit: I restarted the kernel and now this works, I am unsure what caused this before, thank you – elcunyado Jun 24 '20 at 15:59
1

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]
Red
  • 26,798
  • 7
  • 36
  • 58
0

Just append

  player_ids.append(i['id'])
Dori
  • 175
  • 16
  • 6
    I would encourage you to offer more of an explanation with your answers. Do you understand why the original problem occurred? I'm sure you do, so share your insights. – Wyck Jun 24 '20 at 17:51