SunshineTS
SunshineTS

Reputation: 145

Iterating Over a Dictionary

I am trying to return all the values in a dictionary that have a value greater than the int argurment.

def big_keys(dict, int):
    count = []
    for u in dict:
        if u > int:
            count.append(u)
    return count

I don't understand why this isn't working. It returns every value in the list rather than just those which are greater than in.

Upvotes: 0

Views: 943

Answers (2)

Burhan Khalid
Burhan Khalid

Reputation: 174718

By default, any dict will iterate over its keys, not its values:

>>> d = {'a': 1, 'b': 2}
>>> for i in d:
...    print i
... 
a
b

To iterate over values, use .values():

>>> for i in d.values():
...    print i
... 
1
2

With that in mind, your method can be simplified:

def big_keys(d, i):
   return [x for x in d.values() if x > i]

I have changed your variable names, since dict and int are both built-ins.

Your method is actually recreating default functionality available in Python. The filter method does what you are trying to do:

>>> d = {'a': 1, 'b': 6, 'd': 7, 'e': 0}
>>> filter(lambda x: x > 5, d.values())
[6, 7]

From your comment it seems you are looking for the keys and not the values. Here is how you would do that:

>>> d = {'a': 21, 'c': 4, 'b': 5, 'e': 30, 'd': 6, 'g': 4, 'f': 2, 'h': 20}
>>> result = []
>>> for k,v in d.iteritems():
...    if v > 20:
...       result.append(k)
...
>>> result
['a', 'e']

Or, the shorter way:

>>> [k for k,v in d.iteritems() if v > 20]
['a', 'e']

Upvotes: 7

falsetru
falsetru

Reputation: 369424

iterating dictionary yields keys for the dictionary.

>>> d = {'key1': 'value1', 'key2': 'value2'}
>>> for x in d:
...     print(x)
...
key2
key1

To get values, use dict.values():

>>> for x in d.values():
...     print(x)
...
value2
value1

So, you program should read as follow:

def big_keys(dict, int):
    count = []
    for u in dict.values():
        if u > int:
            count.append(u)
    return count

Upvotes: 2

Related Questions