Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick way of getting the keys in a list of dictionaries [duplicate]

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?

like image 436
Huzo Avatar asked May 17 '19 09:05

Huzo


People also ask

How do you get all the keys of a dictionary in a list?

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

Can you duplicate keys in dictionaries?

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.

How do you get a list of all the keys in a dictionary in Python?

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.


1 Answers

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()))
like image 177
dome Avatar answered Nov 10 '22 20:11

dome