The best way to filter a dictionary in Python
35,239
d = dict((k, v) for k, v in d.iteritems() if v > 0)
In Python 2.7 and up, there's nicer syntax for this:
d = {k: v for k, v in d.items() if v > 0}
Note that this is not strictly a filter because it does create a new dictionary.
Author by
leora
Updated on May 19, 2020Comments
-
leora almost 4 years
I have a dictionary of string keys and float values.
mydict = {} mydict["joe"] = 20 mydict["bill"] = 20.232 mydict["tom"] = 0.0
I want to filter the dictionary to only include pairs that have a value greater than zero.
In C#, I would do something like this:
dict = dict.Where(r=>r.Value > 0);
What is the equivalent code in Python?
-
Jeremy Lewis over 12 yearsQuestioner is looking to return a dictionary, this only returns the keys of the dictionary. And it's simply less efficient/Pythonic than @kindall's answer
-
Jeffery almost 7 yearscould be this:
d = dict(filter(lambda x: x[1] > 0.0, d.items()))
-
fraxture over 5 yearsWhat if you want to filter by key?
-
kindall over 5 yearsChange it to test
k
instead ofv
?