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?
You can get all the keys in the dictionary as a Python List. dict. keys() returns an iterable of type dict_keys() . You can convert this into a list using list() .
However, there are a couple restrictions that dictionary keys must abide by. First, a given key can appear in a dictionary only once. Duplicate keys are not allowed.
The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python.
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()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With