python – extract element of a list

  • A+
Category:Languages

I have a list which is like this.

[{0: 26},  {0: 36},  {1: 1},  {0: 215},  {1: 63},  {0: 215}] 

How can I extract another list which has only. [0,0,1,0,1,0]

 


Use dict.keys() to get keys out of a dictionary and use it in a list-comprehension like below:

lst = [{0: 26},        {0: 36},        {1: 1},        {0: 215},        {1: 63},        {0: 215}]  print([y for x in lst for y in x.keys()]) # [0, 0, 1, 0, 1, 0] 

Or, this should be further simplified as:

print([y for x in lst for y in x]) 

Because, when you simply iterate through dictionary like for y in x, you are actually iterating through keys of the dictionary.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: