python - Iterating Over a Dictionary -
i trying return values in dictionary have value greater int argurment.
def big_keys(dict, int): count = [] u in dict: if u > int: count.append(u) return count
i don't understand why isn't working. returns every value in list rather greater in.
by default, dict iterate on keys, not values:
>>> d = {'a': 1, 'b': 2} >>> in d: ... print ... b
to iterate on values, use .values()
:
>>> in d.values(): ... print ... 1 2
with in mind, method can simplified:
def big_keys(d, i): return [x x in d.values() if x > i]
i have changed variable names, since dict
, int
both built-ins.
your method recreating default functionality available in python. filter
method trying do:
>>> d = {'a': 1, 'b': 6, 'd': 7, 'e': 0} >>> filter(lambda x: x > 5, d.values()) [6, 7]
from comment seems looking keys , not values. here how that:
>>> d = {'a': 21, 'c': 4, 'b': 5, 'e': 30, 'd': 6, 'g': 4, 'f': 2, 'h': 20} >>> result = [] >>> k,v in d.iteritems(): ... if v > 20: ... result.append(k) ... >>> result ['a', 'e']
or, shorter way:
>>> [k k,v in d.iteritems() if v > 20] ['a', 'e']
Comments
Post a Comment