简体   繁体   English

返回列表中字典值的列表

[英]Return a list of values of dictionaries inside a list

I have a list that contains dictionaries, each of them have the same keys and different values, 我有一个包含字典的列表,每个字典都有相同的键和不同的值,

How can I get a list of values of every dictionary in the list? 如何获得列表中每个字典的值的列表?

With dictionary.values() I can get a list of values of a dictionary but what if it is inside an array? 使用dictionary.values()我可以获得字典值的列表,但是如果它在数组中怎么办?

Is it necessary to do a for-loop to get every dictionary in the list? 是否有必要进行for循环以获取列表中的每个字典?

This is what I want: 这就是我要的:

list= [{'a':0,'b':1,'c':2}, {'a':3,'b':4,'c':5}, {'a':6,'b':2,'c':3},]

all_values = [0,1,2,3,4,5,6] # THIS IS THE ACTUAL QUESTION

values_of_a = [0,3,6]  # THIS COULD BE BETTER IF POSSIBLE

You can use list comprehensions for both tasks: 您可以对两个任务使用列表推导:

>>> array = [{'a':0,'b':1,'c':2}, {'a':3,'b':4,'c':5}, {'a':6,'b':2,'c':3},]
>>> [y for x in array for y in x.values()]
[0, 1, 2, 3, 4, 5, 6, 2, 3]
>>> [x['a'] for x in array]  # Assuming that all dicts have an 'a' key
[0, 3, 6]
>>>

Also, array is not technically an array. 同样, array在技​​术上不是数组。 It is a list . 这是一个清单 Arrays in Python are instances of array.array . Python中的数组是array.array实例。

Or you can use lambda : 或者您可以使用lambda

>> b = map(lambda x: x.values(), a)
>> reduce(lambda x, y: x+ y, b)
>> [0, 2, 1, 3, 5, 4, 6, 3, 2]
>> map(lambda x: x['a'], a)
>> [0, 3, 6]

You use a for loop: 您使用一个for循环:

all_values = []
for d in array:
    all_values.extend(d.values())

values_of_a = []
for d in array:
    values_of_a.append(d["a"])

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

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