Skip to content

Instantly share code, notes, and snippets.

@89465127
Created June 13, 2013 20:05
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save 89465127/5776892 to your computer and use it in GitHub Desktop.
Save 89465127/5776892 to your computer and use it in GitHub Desktop.
python filter a dictionary by keys or values
d = {1:11, 2:22, 3:33}
# filter by key
d2 = {k : v for k,v in filter(lambda t: t[0] in [1, 3], d.iteritems())}
# filter by value
d3 = {k : v for k,v in d.iteritems() if k in [2,3]}
@Lane012
Copy link

Lane012 commented Apr 3, 2018

shouldn't the if k in [2,3] be a v not a k on line 7 if filtering by value?

@w2ak
Copy link

w2ak commented Apr 6, 2018

It's actually not filtering by keys or by values, @Lane012. I think he meant that you can either filter before iterating in for (using filter), or after iterating in for, using the 'if'.

@fbens
Copy link

fbens commented Jul 17, 2018

>>> d = {1:11, 2:22, 3:33}
>>> d
{1: 11, 2: 22, 3: 33}
>>> d.iteritems()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'iteritems'
>>>

@bmbove
Copy link

bmbove commented Jul 24, 2018

@fbens iteritems is gone if you're using python 3. try d.items() instead

@vaibhavkhulbe
Copy link

can use this for value search
d3 = {k : v for k,v in filter(lambda t: t[1] in [22, 33], d.iteritems())}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment