NEW_user 2020
NEW_user 2020

Reputation: 65

Remove dictionary element based on dict.values()

If the string 'email' is not in dict values, I want to delete the corresponding element, so i did the following:

[ my_dict.pop(k) for k , val in my_dict.items() if 'email' not in val ]

So any better solution to do that?
Is it better to write a long line of code like above or to do the following:

    for k , val in my_dict.items():
        if 'email' not in val:
            my_dict.pop(k)

Upvotes: 1

Views: 48

Answers (2)

ingofreyer
ingofreyer

Reputation: 1164

You are deleting based on an aspect of the value. In my eyes, your approach is not bad, especially if you would be tight on available memory.

Another approach would be a dictionary comprehension, which should be slightly faster but uses more memory since you would be copying over the old dictionary into a new one:

my_dict = {key: val for key, val in my_dict.items() if 'email' not in val}

As far as I remember, dictionary comprehensions like this have been introduced in Python 2.7. Alternatively, you could also do this:

dict = my_dict([(key, val) for key, val in my_dict.items() if 'email' not in val])

I would recommend choosing between your current approach and mine based on the expected size of the dictionary and memory restrictions.

Upvotes: 1

Jasmijn
Jasmijn

Reputation: 10452

Don't use a list comprehension if you're not going to use the list! Similarly, don't use dict.pop if you're not going to use the popped value. It's also not a good idea to override builtin names like dict. More pythonic would be:

for key, val in my_dict.items():
    if 'email' not in val:
        del my_dict[key]

Upvotes: 1

Related Questions