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.
-
1If 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.SethMMorton– SethMMorton2013-12-17 03:45:39 +00:00Commented Dec 17, 2013 at 3:45
Add a comment
|
3 Answers
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.
Comments
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