Consider the example below:
m = [{'a':1},{'b':2}]
I wanted to find a short way of forming a list of the keys in m
, just like ['a','b']
. What would be the shortest or the easiest way rather than using traditional for loops? Perhaps a syntactic sugar?
Asked
Active
Viewed 457 times
5

Huzo
- 1,652
- 1
- 21
- 52
4 Answers
10
You can use list comprehension, a sintactic sugar of for loops:
keys_list = [x for d in m for x in d.keys()]
Note that if your dictionaries have keys in common they will be appear more than once in the result.
If you want only unique keys, you can do this:
keys_list = list(set(x for d in m for x in d.keys()))

dome
- 820
- 7
- 20
-
But that does not give a string right? That gives something like `[dict_keys(['a']), dict_keys(['b'])]`, instead of `['a','b']` – Huzo May 17 '19 at 09:20
-
Yea, now i change the answe, sorry. – dome May 17 '19 at 09:21
-
You can even write it more simply: `[x for x in d for d in m]` because iterating over a dictionary returns the keys. – Serge Ballesta May 17 '19 at 09:23
-
Thank you, didn't know. If you don't mind I edit the post with your suggestion. – dome May 17 '19 at 09:24
-
I already have that approach in my answer @dome I think you might want to avoid duplication ? – Devesh Kumar Singh May 17 '19 at 09:25
-
Sorry, didn't see. – dome May 17 '19 at 09:27
-
did you test this code ? @dome – ncica May 17 '19 at 09:32
-
Just corrected the error. – dome May 17 '19 at 09:34
-
Not sure how the last approach gives unique keys, just try it with `m = [{'a':1, 'b':2},{'a':3,'b':4}]` – Devesh Kumar Singh May 17 '19 at 09:39
-
You are right, corrected it. – dome May 17 '19 at 09:42
-
Cool, +1 for the correction. Could you upvote my answer as well :) – Devesh Kumar Singh May 17 '19 at 09:50
-
Yes, of course. – dome May 17 '19 at 09:52
7
A simple double for-loop with list-comprehension should do the trick. Iterate over the list, and for each element in the list, iterate over the keys
In [5]: m = [{'a':1},{'b':2}]
In [6]: [k for item in m for k in item]
Out[6]: ['a', 'b']
If the list has duplicate keys, just convert the final output to a set and then to a list to get unique keys
In [19]: m = [{'a':1, 'b':2},{'a':3,'b':4}]
In [20]: r = [k for item in m for k in item]
In [21]: r
Out[21]: ['a', 'b', 'a', 'b']
In [22]: r = list(set(r))
In [23]: r
Out[23]: ['b', 'a']

Devesh Kumar Singh
- 20,259
- 5
- 21
- 40
2
- Extract all dicts keys to a list of lists
- Convert them to one list by itertools.chain
from itertools import chain
a = [{'a': 1, 'c': 2}, {'b': 2}]
b = [d.keys() for d in a]
list(chain(*b))
will return:
['c', 'a', 'b']

vurmux
- 9,420
- 3
- 25
- 45
1
If you want just unique keys do this:
m = [{'a':1},{'b':2},{'b':3}]
print({x for d in m for x in d})
and this one contains duplicates:
print([x for d in m for x in d])

alireza yazdandoost
- 634
- 7
- 11