-5
def big_keys(dicta,x):
    for k in dicta:
        if x < dicta.get(k,0):
            return k

for this function, I want it to input dicta which is a dictionary and x is int. and it should return all the k that have value more than x. however it only return one of the k and not all of them. e.g big_keys({"a":20 ,"b":20 ,"c":10},15)["a", "b"]
but my out put is ["a"]

deceze
  • 510,633
  • 85
  • 743
  • 889
Ali Mozard
  • 15
  • 3

1 Answers1

1

A minimum effort solution would be to gather all suitable k in a list and return that list:

def big_keys(dicta,x):
    results = []
    for k in dicta:
        if x < dicta.get(k,0):
            results.append(k)

However you can write that more compactly and efficient with list comprehension:

def big_keys(dicta, x):
    return [k for k in dicta if x < dicta[k]]

note that there is no need for dicta.get(k, 0), as k in dicta is guaranteed by the fact that we're iterating over dicta.

EDIT: iterating over dicta.items() instead of calling dicta[k] is of course also valid; I'm not sure if one is significantly faster than the other …

EDIT: Just ran a simple timeit and dicta.items() is indeed faster

CallMeStag
  • 5,467
  • 1
  • 7
  • 22