简体   繁体   English

[python - 获取字典列表中的键列表]

[英][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', ...]. x 中每个字典 d 的键列表作为d.keys()获得,这将产生类似 ['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因此,如果您编写,您还将获得列表 ['id', 'number',...]

>>> [ 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 .x不是list而是setdict时,获取第一个元素会更加棘手。 In that case you can use next(x.__iter__()) .在这种情况下,您可以使用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'. PS:您实际上应该考虑您真正想要的键是什么-先验应该是“id”,而不是“数字”,但是您的“id”有重复项,这与“id”的概念和定义/含义相矛盾' - 然后使用选择的键作为标识符来索引集合'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 .然后您也可以执行例如x[123]['count'] += 1来增加条目123的 'count' 。

Using a functional programming approach:使用函数式编程方法:

from operator import itemgetter

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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