Home > database >  Filter dictionaries from a list based on condition Python
Filter dictionaries from a list based on condition Python

Time:11-24

I have a list of dictionaries with all dictionaries having a structure similar to this: list_of_dict = {'a': 0, 'b':1, 'c': 1, 'd':0, 'e':0, ...}, i.e. the dictionaries will contain all the alphabets as the keys and it can have only 0, 1 or -1 as their corresponding values. Also, I have a list of keys that are dynamically fetched, for example: filter_list = ['b', 'e', 'g']

I want to filter the list_of_dict in such a way that I filter all the dictionaries from the list_of_dict such that I get only the dictionaries for which all values corresponding to the filter_list are zero (0)

My code so far is this:

def filter_list():
    zero_list = ['b', 'e', 'g']
    list_of_all_dict = [
              {'a': 0, 'b':1, 'c': 1, 'd':0, 'e':0, ...},
              {'a': 1, 'b':0, 'c': 0, 'd':1, 'e':0, ...},
          ]
    filtered_list = list()
    for d in list_of_all_dict:
        flag = True
        for c in zero_list:
            if d[c] != 0:
                flag = False
        if flag:
            filtered_list.append(d)
    return filtered_list

It works, but I was wondering if there is a better approach in Python; maybe with a list(filter(lambda x: all(...))) approach that I am unable to think of at this point. I am not really stuck, but I found this while refactoring my code and was wondering if there is a better approach.

Any suggestion or advice is welcome. Thank you in advance!

CodePudding user response:

I don't understand why you're defining zero_list and list_of_all_dict inside your function. Shouldn't the function take them as arguments?

Regarding the logic, you can use all instead of using a flag. Add a comprehension and your function fits in one line:

# this will generate dictionaries easily:
import random
import string

LIST_LENGTH = 10

list_of_all_dict = [
    dict(zip(string.ascii_lowercase, random.choices([-1, 0, 1], k=26)))
    for _ in range(LIST_LENGTH)
]

# define zero list here:
zero_list = ['b', 'e', 'g']

# your function:
def filter_list(dict_list, zero_lst):
    return [d for d in dict_list if all(d[k]==0 for k in zero_lst)]

print(filter_list(list_of_all_dict, zero_list))
  • Related