Home > other >  [python - get the list of keys in a list of dictionary]
[python - get the list of keys in a list of dictionary]

Time:06-10

I have a list of dictionaries
input:

x = [{'id': 19, 'number': 123, 'count': 1}, 
     {'id': 1, 'number': 23, 'count': 7}, 
     {'id': 2, 'number': 238, 'count': 17},
     {'id': 1, 'number': 9, 'count': 1}]

How would I get the list of number:

[123, 23, 238, 9]

Thank you for you reading

CodePudding user response:

You can use a list comprehension:

numbers = [dictionary.get('number') for dictionary in list_of_dictionaries]

CodePudding user response:

To get these numbers you can use

>>> [ d['number'] for d in x ]

But this is not the "list of keys" for which you ask in the question title. The list of keys of each dictionary d in x is obtained as d.keys() which would yield something like ['id', 'number', ...]. Do for example

>>> [ list(d.keys()) for d in x ]

to see. If they are all equal you are probably only interested in the first of these lists. You can get it as

>>> list( x[0].keys() )

Note also that the "elements" of a dictionary are the keys rather than the values. So you will also get the list ['id', 'number',...] if you write

>>> [ key for key in x[0] ]

or even simply:

>>> list( x[0] )

To get the first element is more tricky when x is not a list but a set or dictionary. In that case you can use next(x.__iter__()).

  • Related