1

I have a dictionary with a large number of entries I want to remove.I can write a regular expression to find them all, but I don't know how to delete them all.

1
  • 1
    If you notice, there are three different answers that each answer a different question. This indicates your question is not clear. You might want to make what you want more clear so you get an answer that best fits your question. Commented Dec 17, 2013 at 3:45

3 Answers 3

2

Iterate over the dict and build a new dict containing only the elements you want to keep:

new_dict = {key: value for key, value in old_dict.iteritems() if keep(key, value)}

You can also do it by deleting items from the old dict with del, but modifying something while you iterate over it is tricky business. It's usually best not to do it.

Sign up to request clarification or add additional context in comments.

Comments

1

The del statement does exactly that.

def remove(dic, key):
    re = dict(dic)
    del re[key]
    return re

Comments

0

To delete a regex match we could use the re.sub(pattern,replace_with,string) method, The key is top make the replace_with a empty string so that a match is replaced with a empty string:

For example, This script will remove all non-digit characters:

import re

string = "My age is 99"
print re.sub('\D+','',string)

Output:

99

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.