zinon zinon - 4 months ago 17
Python Question

Python: Extract dict value from list of dict

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?


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]