Paul Gomez
Paul Gomez

Reputation: 25

How to filter through a dictionary with a list of dictionaries inside

Dictionary = {'list': [{'id': 1, 'task': 'Harry', 'completed': False}, {'id': 2, 'task': 'Simon', 'completed': True}]}

I want to filter through this Dictionary all the items with completed = True and add it to another list

Upvotes: 0

Views: 63

Answers (3)

Sebastian Henao
Sebastian Henao

Reputation: 1

probably this could help you

list_items = {'list': [{'id': 1, 'task': 'Harry', 'completed': False}, 
          {'id': 2, 'task': 'Simon', 'completed': True}],
          'list_2': [{'id': 1, 'task': 'helena', 'completed': False}, 
          {'id': 2, 'task': 'carlos', 'completed': True}]}
new_list = []
for list_name in list_items:
    for list_of_dict in list_items[list_name]:
        if list_of_dict["completed"] == True:
            new_list.append(list_of_dict)
[{'id': 2, 'task': 'Simon', 'completed': True},
 {'id': 2, 'task': 'carlos', 'completed': True}]

Upvotes: -1

Mr. Hobo
Mr. Hobo

Reputation: 552

If you have a single key in the dictionary, you can do this via a single line expression as:

d = {'list': [{'id': 1, 'task': 'Harry', 'completed': False}, {'id': 2, 'task': 'Simon', 'completed': True}]}

li = [i for i in d['list'] if i['completed']]
print(li)

>> [{'id': 2, 'task': 'Simon', 'completed': True}]

Now, considering you have multiple key in dictionary, then:

d = {
    'list1': [{'id': 1, 'task': 'Harry', 'completed': False}, {'id': 2, 'task': 'Simon', 'completed': True}],
    'list2': [{'id': 1, 'task': 'Harry', 'completed': False}, {'id': 2, 'task': 'Simon', 'completed': True}],
}

all_items = []
new_filter_d = dict() # get sub list based on each different key

for k, v in d.items():
    all_items += [i for i in v if i['completed']]
    new_filter_d[k] = [i for i in v if i['completed']]

print(all_items)
>> [{'id': 2, 'task': 'Simon', 'completed': True},
 {'id': 2, 'task': 'Simon', 'completed': True}]

print(new_filter_d)
>> {'list1': [{'id': 2, 'task': 'Simon', 'completed': True}],
 'list2': [{'id': 2, 'task': 'Simon', 'completed': True}]}

Upvotes: 1

azazazaza
azazazaza

Reputation: 83

if the only key of the base dictionary is list, then just iterate over its contents and append it to a list

completed = []
for d in dictionary["list"]:
    if d["completed"]:
        completed.append(d)

or as a list comprehension:

completed = [d for d in dictionary["list"] if d["completed"]]

Upvotes: 2

Related Questions