简体   繁体   中英

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?

Is it necessary to do a for-loop to get every dictionary in the list?

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. It is a list . Arrays in Python are instances of array.array .

Or you can use 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:

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

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

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