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
  • 119,623
  • 25
  • 170
  • 301
zinon
  • 4,427
  • 14
  • 70
  • 112

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,797
  • 3
  • 30
  • 42
5

I think you want:

[a["id"] for a in x]
Nils Gudat
  • 13,222
  • 3
  • 39
  • 60
1

You can use itemgetter from operator:

y = list(map(itemgetter('id'), x))
hilberts_drinking_problem
  • 11,322
  • 3
  • 22
  • 51