def big(dict, n):
line = []
for k in dict:
if k > n:
line.append(k)
return line
I have to find all the elements in dict larger than n.
However, my code only returns the largest number in dict larger than n.
What do I need to do in order to make it correct?
The
return lineis tabbed too far over, so it returns when the first key larger thannis found (Note: a dictionary isn’t ordered by the way you write it), rather than going over all keys before returning. Try:In fact, you might prefer it to use list comprehension (and the function becomes just one line).
.
Dictionaries compomise of key value pairs,
{key: value}and when we iterate over a dictionary we are iterating over it’s keys. This explains the use of the variablekto iterate over the keys. That is,Hence, if you want to find that with the largest value in the dictionary, you can use:
Note: I’ve changed the variable name to
dicsince (as @AndrewJaffe mentions)dictis a built-in object, and renaming it here may cause unexpected things to occur, and is generally considered bad practise. For example, if you wanted to checktype(dic)==dict.