-1

I have a list which is like this:

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

How can I extract a list of keys from it?

[0, 0, 1, 0, 1, 0]
Georgy
  • 12,464
  • 7
  • 65
  • 73
Ayman Alawin
  • 93
  • 1
  • 10

8 Answers8

4

Use dict.keys to extract the keys of each of the dict, convert to a list, and then extract the first element

>>> lst = [{0: 26}, {0: 36}, {1: 1}, {0: 215}, {1: 63}, {0: 215}]
>>> [list(d.keys())[0] for d in lst]
[0, 0, 1, 0, 1, 0]

Alternatively, you can use list comprehension as below

>>> [k for d in lst for k in d.keys()]
[0, 0, 1, 0, 1, 0]
Sunitha
  • 11,777
  • 2
  • 20
  • 23
  • 3
    Or `[next(iter(i)) for i in L]`. Please can you rename your list, in many fonts `l` looks the same as `I`. In addition, you don't need to use `d.keys()`. `d` should suffice when iterating or using `list(d)`. – jpp Aug 15 '18 at 08:43
4

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.

Austin
  • 25,759
  • 4
  • 25
  • 48
2

I suggest you to simply iterate over the list of dictionaries, and to iterate over the keys of each dictionary, using list comprehension as follows:

myList = [{0: 26}, {0: 36}, {1: 1}, {0: 215}, {1: 63}, {0: 215}]
newList = [k for d in myList for k in d]
print(newList) # [0, 0, 1, 0, 1, 0]
Laurent H.
  • 6,316
  • 1
  • 18
  • 40
1

Those are the keys so you would use the dict.keys() method:

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

L2 = [list(d.keys())[0] for d in L]
Mathieu
  • 5,410
  • 6
  • 28
  • 55
1

use keys() function of dict().

a = [{0: 26}, {0: 36}, {1: 1}, {0: 215}, {1: 63}, {0: 215}]
keys = list(a.keys()[0])
vaues = (a.values()[0]) 

Cheers!

SanthoshSolomon
  • 1,383
  • 1
  • 14
  • 25
1

you can do it this way :

list = [list(d.keys())[0] for d in originalList] #  originalList is the first list you posted

Here's the output : [0, 0, 1, 0, 1, 0]

Ines Tlili
  • 790
  • 6
  • 21
1

You can use dict.keys and itertools.chain to build a list of all keys:

from itertools import chain

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

keys = list(chain.from_iterable(map(dict.keys, w)))
Daniel
  • 42,087
  • 4
  • 55
  • 81
1

OR try the below code, using map:

lod=[{0: 26},
 {0: 36},
 {1: 1},
 {0: 215},
 {1: 63},
 {0: 215}]
print(list(map(lambda x: list(x.keys())[0])))
U13-Forward
  • 69,221
  • 14
  • 89
  • 114