41

I need to select elements of a dictionary of a certain value or greater. I am aware of how to do this with lists, Return list of items in list greater than some value.

But I am not sure how to translate that into something functional for a dictionary. I managed to get the tags that correspond (I think) to values greater than or equal to a number, but using the following gives only the tags:

[i for i in dict if dict.values() >= x]
smci
  • 32,567
  • 20
  • 113
  • 146
Jesse O
  • 421
  • 1
  • 4
  • 4

3 Answers3

55

.items() will return (key, value) pairs that you can use to reconstruct a filtered dict using a list comprehension that is feed into the dict() constructor, that will accept an iterable of (key, value) tuples aka. our list comprehension:

>>> d = dict(a=1, b=10, c=30, d=2)
>>> d
{'a': 1, 'c': 30, 'b': 10, 'd': 2}
>>> d = dict((k, v) for k, v in d.items() if v >= 10)
>>> d
{'c': 30, 'b': 10}

If you don't care about running your code on python older than version 2.7, see @opatut answer using "dict comprehensions":

{k:v for (k,v) in dict.items() if v > something}
Community
  • 1
  • 1
nmaier
  • 32,336
  • 5
  • 63
  • 78
  • 2
    This is great! Could you explain the how the syntax of this actually works (like I'm five)? – Jesse O Sep 18 '13 at 15:25
  • @JesseO I just added enough explanation with enough doc links so that you either understand it (if you're a little fluent in python), or can work it out yourself. – nmaier Sep 18 '13 at 15:38
21

While nmaier's solution would have been my way to go, notice that since python 2.7+ there has been a "dict comprehension" syntax:

{k:v for (k,v) in dict.items() if v > something}

Found here: Create a dictionary with list comprehension in Python. I found this by googling "python dictionary list comprehension", top post.

Explanation

  • { .... } includes the dict comprehension
  • k:v what elements to add to the dict
  • for (k,v) in dict.items() this iterates over all tuples (key-value-pairs) of the dict
  • if v > something a condition that has to apply on every value that is to be included
Community
  • 1
  • 1
opatut
  • 6,708
  • 5
  • 32
  • 37
9

You want dict[i] not dict.values(). dict.values() will return the whole list of values that are in the dictionary.

dict = {2:5, 6:2}
x = 4
print [dict[i] for i in dict if dict[i] >= x] # prints [5]
Shashank
  • 13,713
  • 5
  • 37
  • 63