Extract dict value from list of dict? [duplicate]

一笑奈何 提交于 2019-12-01 14:23:23

问题


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?


回答1:


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]



回答2:


I think you want:

[a["id"] for a in x]



回答3:


You can use itemgetter from operator:

y = list(map(itemgetter('id'), x))


来源:https://stackoverflow.com/questions/37463569/extract-dict-value-from-list-of-dict

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!