Search and Remove from Dictionary

This is the place for queries that don't fit in any of the other categories.

Search and Remove from Dictionary

Postby mrotsliah » Thu Mar 27, 2014 3:11 pm

I'm still kinda new to python. My main question: Is there a standard python algorithm that searches a dictionary and removes entries that satisfy a certain requirement?

I was writing my own using a for loop, but then the compiler yelled at me for popping entries in the middle of a for loop. So then I thought I would start making a new dictionary with the entries I would remove later once the for loop ran its course. But then I had trouble using the dictionary update() function whilst indexing with the keys.

My code is kinda complicated. So I can give sudo code for what I am trying to do for the latter situation mentioned here.

Code: Select all
def Remove_Function(DD):
    for d in DD:
        if "test condition on d is True":
   for k in data:
   return DD

Any suggestions or help is appreciated.

Thank you.
Posts: 4
Joined: Wed Dec 11, 2013 8:49 pm

Re: Search and Remove from Dictionary

Postby Mekire » Thu Mar 27, 2014 3:46 pm

The most common way would be to just make a new dict with a comprehension:

Code: Select all
some_dict = {"a":1, "b":2, "c":3, "d":4}

def remove_evens(my_dict):
    return {k:v for k,v in my_dict.items() if v%2}
This won't change the original dict; it will construct and return a new one.
Code: Select all
>>> some_dict
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> some_dict = remove_evens(some_dict)
>>> some_dict
{'a': 1, 'c': 3}

If you really need to change the dict in place you can do stuff like this:
Code: Select all
def remove_evens_ip(my_dict):
    for k,v in list(my_dict.items()):
        if not v%2:
            del my_dict[k]
Code: Select all
>>> some_dict
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
>>> remove_evens_ip(some_dict)
>>> some_dict
{'a': 1, 'c': 3}

New Users, Read This
  • Use code tags when posting code.
  • Include any errors with your post (in code tags).
  • Describe your problem; not your chosen solution.
  • Make examples the minimum length to demonstrate your issue.
User avatar
Posts: 1711
Joined: Thu Feb 07, 2013 11:33 pm
Location: Tucson, Arizona

Return to General Coding Help

Who is online

Users browsing this forum: Yahoo [Bot] and 8 guests