简体   繁体   中英

Extract keys from a list of dicts with single key-value pairs

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]

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]

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.

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]

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]

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!

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]

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)))

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])))

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