0

I have this parameter

x = [{'id': 1L}, {'id': 4L}]

My list contains dicts that contain long integers, so there is a need to convert them to integers.

I want to save only values of id in a new list like

y = [1, 4]

Do you know how to do this?

martineau
  • 112,593
  • 23
  • 157
  • 280
zinon
  • 4,077
  • 11
  • 64
  • 99

3 Answers3

9

You can use a list comprehension:

ids = [y['id'] for y in x]

This assumes that every dictionary has a key 'id'. If you're not sure that key exists in every dictionary, you can use this one:

ids = [y['id'] for y in x if 'id' in y]
Kristof Claes
  • 10,617
  • 3
  • 29
  • 41
5

I think you want:

[a["id"] for a in x]
Nils Gudat
  • 11,046
  • 3
  • 33
  • 51
1

You can use itemgetter from operator:

y = list(map(itemgetter('id'), x))
hilberts_drinking_problem
  • 10,973
  • 3
  • 19
  • 46