简体   繁体   中英

Remove dict structure from list in python

Say I have a list of dicts looking like this:

self = [ {x: '1'}, {x: '7'}, {x: '8'}, {x: '9'}, {x: '1'}, {x: '4'}, {x: '7'}, {x: '7'}, {x: '7'}, {x: '7'} ]

And I want to remove all dict structures and only keeping their elements, to end up with a list looking like this:

[1,7,8,9,1,4,7,7,7,7]

Is there any function in python supporting that?

You can do something like this :

lst = [ {'x': '1'}, {'x': '7'}, {'x': '8'}, {'x': '9'}, {'x': '1'}, {'x': '4'}, {'x': '7'}, {'x': '7'}, {'x': '7'}, {'x': '7'} ]
print([int(a.get('x')) for a in lst])

This will result in :

[1, 7, 8, 9, 1, 4, 7, 7, 7, 7]

Note that the dictionaries inside the list have keys as 'x' instead of x as declared in the question.

You can also use the map function

a = [{'x': '1'}, {'x': '7'}, {'x': '8'}, {'x': '9'}, {'x': '1'}, {'x': '4'}, {'x': '7'}, {'x': '7'}, {'x': '7'}, {'x': '7'}]

b = list(map(lambda e: e['x'], a))

print (b)

Result:

['1', '7', '8', '9', '1', '4', '7', '7', '7', '7']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM