Jubick
Jubick

Reputation: 447

How do I remove certain items from the dictionary?

I'm trying to filter responses from server that i store in dictionary. Dictionary contains lists. I want to delete every list in each key where list doesn't contain 5 items.

I tried code like this

def mutate_res(dic):
    for key in dic.keys():
        for response in dic[key]:
            if len(response) != 5:
                dic[key].remove(response)
    return dic

I expect dic[value] have only lists that contain 5 items but it's not working, it may have 3 or 5 items

Upvotes: 1

Views: 77

Answers (3)

Patrick Artner
Patrick Artner

Reputation: 51683

You get the keys to delete and delete them:

def mutate_res(dic):
    delete_me = [ k for k in dic if len(dic[k])!=5]
    for k in delete_me:
        del dic[k] 
    return dic

This does not delete anything while iterating so it is safe to do so.


Misread your data-structure - to remove inner lists of lenght != 5 you can do:

def mutate_res(dct):
    delete_me = [ k for k in dct if any(len(inner)!=5 for inner in dct[k])]
    for k in delete_me:
        dct[k] = [inner for inner in dct[k] if len(inner) == 5]
    return dct

d = {1: [ [1,],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]}

print(mutate_res(d)) # {1: [[1, 2, 3, 4, 5]]}

Upvotes: 3

Mark
Mark

Reputation: 92461

Since you don't need to mutate the dictionary in place, you can just use a comprehension and return the correct dictionary. Although I would consider changing the name of the function in that case so it's not misleading.

def mutate_res(dic):
    return {k:v for k,v in dic.items() if len(v) == 5}

d = {
    'a': [1, 2, 3, 4, 5],
    'b': [1,2],
    'c': [1, 2, 3, 4, 5, 6],
    'd': [1, 2, 3, 4, 5]
}
mutate_res(d)
>> {'a': [1, 2, 3, 4, 5], 'd': [1, 2, 3, 4, 5]}

Upvotes: 2

jspcal
jspcal

Reputation: 51934

You could modify your code to use a list comprehension that filters out the unwanted elements:

def mutate_res(dic):
    for key in dic.keys():
        dic[key] = [x for x in dic[key] if len(x) != 5]

Upvotes: 0

Related Questions