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.

Share:
35,239
leora
Author by

leora

Updated on May 19, 2020

Comments

  • leora
    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
    Jeremy Lewis over 12 years
    Questioner 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
    Jeffery almost 7 years
    could be this: d = dict(filter(lambda x: x[1] > 0.0, d.items()))
  • fraxture
    fraxture over 5 years
    What if you want to filter by key?
  • kindall
    kindall over 5 years
    Change it to test k instead of v?