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?
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']
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()))
[x for x in d for d in m]
because iterating over a dictionary returns the keys. –
Castora m = [{'a':1, 'b':2},{'a':3,'b':4}]
–
Phyto 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']
- 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']
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])
© 2022 - 2024 — McMap. All rights reserved.
[dict_keys(['a']), dict_keys(['b'])]
, instead of['a','b']
– Brute