Home > Blockchain >  How to filter dictionary values according to a given list of values?
How to filter dictionary values according to a given list of values?

Time:11-09

I have a list and a dictionary:

my_list = ['white', 'grey', 'black']

my_dict = {'name1': ['green', 'yellow', 'orange', 'black'],
           'name2': ['red', 'yellow', 'orange', 'purple', 'white', 'black'],
           'name3': ['blue', 'red', 'grey', 'orange', 'black']}

I want to get a filtered dictionary according to a list:

my_new_dict = {'name1': ['black'],
               'name2': ['white', 'black'],
               'name3': ['grey', 'black']}

What I started doing:

my_new_dict = {}
for k, v in my_dict.items():
    for x in v:
        temp_list = list()
        if x in my_list:
            temp_list.append(x)
            my_new_dict[k] = temp_list

As a result, I get a dictionary with only 1 element "black":

print(my_new_dict)

{'name1': ['black'], 'name2': ['black'], 'name3': ['black']}

Help fix this. Thank you.

CodePudding user response:

I would use a dictionary comprehension here.

>>> my_list = ["white", "grey", "black"]
>>>
>>> my_dict = {
...     "name1": ["green", "yellow", "orange", "black"],
...     "name2": ["red", "yellow", "orange", "purple", "white", "black"],
...     "name3": ["blue", "red", "grey", "orange", "black"],
... }
>>>
>>> result = {
...     name: [item for item in list_ if item in my_list] for name, list_ in my_dict.items()
... }
>>> print(result)
{'name1': ['black'], 'name2': ['white', 'black'], 'name3': ['grey', 'black']}

But if you prefer to use your current solution, you have to make the following changes(At the moment your list gets re-initialized on every iteration of v).

my_new_dict = {}
for k, v in my_dict.items():
    temp_list = []
    for x in v:
        if x in my_list:
            temp_list.append(x)
    my_new_dict[k] = temp_list

print(my_new_dict)
  • Related