简体   繁体   中英

How to do list comprehension on a list of dictionaries without returning values in a list?

I'm trying to perform list comprehension on a list of dictionaries. Using an example I found here , works, but returns a list of lists. This is the code I am using:

transaction_types=[[v for k,v in t.items() if 'transaction_type' in k] for t in all_transactions]. 

Which would return a list as such: [['deposit'], ['withdrawal'], ['withdrawal'], ['withdrawal'], ['deposit'], ['closed account']]

How can I do the same, but without returning the values inside of a list? The result would look like so: ['deposit', 'withdrawal', 'withdrawal', 'withdrawal', 'deposit', 'closed account'].

Dropping the list inside of the list comprehension like so:

transaction_types=[[v for k,v in t.items() if 'transaction_type' in k] for t in all_transactions]. 

just returns the first value of the dictionary * the number of dictionaries. Eg : [['deposit'], ['deposit'], ['deposit'], ['deposit'], ['deposit'], ['deposit']]

Using technique from: How to convert a nested loop to a list comprehension in python we have the following two equivalent solutions.

List Comprehension

 transaction_types=[v for t in all_transactions for k,v in t.items() if 'transaction_type' in k]

Double For Loop

transaction_types = []
for t in all_transactions:
    for k, v in t.items():
        if 'transaction_type' in k:
            transaction_types.append(v)

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