简体   繁体   中英

Take Min key with same values in Dict

I have a dict

x={1:1,2:2,3:8,4:8,5:2,6:7,7:4,8:9,10:2}

I want to define a function f(i) that returns the key having the value i .

Now that multiple keys have the same values, the min key should be returned.

Ex- i=2 then in x, 2,5 and 10 has value i=2

So 2 must be returned.

i=8

3 and 4 have value 8 then 3 must be returned.

Is it possible to do this without using loops, as this function act as a base function and will be called from other function multiple times ( approx up to 10^18 )? I want to write this function without a loop. Is it possible?

The easiest would be

def f(dictionary, target_value):
    return min(filter(lambda k: dictionary[k] == target_value, dictionary.keys()))

Make use of min and dict comprehnesion

def find(i):
    return min({k:v for k,v in x.items() if v == i}.keys())
print(find(2))

output

2

One way to do it without directly using loops, is to use the filter() function along with the min() :

x={1:1,2:2,3:8,4:8,5:2,6:7,7:4,8:9,10:2}

def f(i):
    global x
    return min(filter(lambda k: x[k] == i, x))

NOTE: Although I use global to be able to use x inside f() , it is better to add one more argument in f() to avoid globals:

def f(x, i):
    return min(filter(lambda k: x[k] == i, x))

Testing it with the examples you provided in your question:

print(f(2))
print(f(8))

will return:

2
3

This would definitely work fine in your case try the below solution

def findMinIndexElement(to_find):
    values = list(x.values())
    keys = list(x.keys())
    try:
        return keys[values.index(to_find)]
    except:
        return 'Not Found'
        

x={1:1,2:2,3:8,4:8,5:2,6:7,7:4,8:9,10:2, 11:7}
to_find = int(input())
print(findMinIndexElement(to_find))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM