简体   繁体   中英

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

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

您可以使用列表推导:

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

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 actually 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 simply (and better):

>>> list( x[0] )

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

PS: You should actually think what you really want the keys to be -- a priori that should be the 'id's, not the 'number's, but your 'id's have duplicates which is contradictory to the concept and very definition / meaning of 'id' -- and then use the chosen keys as identifiers to index the elements of your collection 'x'. So if the keys are the 'number's, you should have a dictionary (rather than a list)

x = {123: {'id': 19, 'count': 1}, 23: {'id': 1, 'count': 7}, ...}

(where I additionally assumed that the numbers are indeed integers [which is more efficient] rather than strings, but that's up to you). Then you can also do, eg , x[123]['count'] += 1 to increment the 'count' of entry 123 .

Using a functional programming approach:

from operator import itemgetter

x_k = list(map(itemgetter('number'), x))
#[123, 23, 238, 9]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM