Home > Software engineering >  How to do list comprehension on a list of dictionaries without returning values in a list?
How to do list comprehension on a list of dictionaries without returning values in a list?

Time:12-10

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. E.g. : [['deposit'], ['deposit'], ['deposit'], ['deposit'], ['deposit'], ['deposit']]

CodePudding user response:

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)
  • Related