Home > Software design >  How to get multiple keys from same value in Python dictionary
How to get multiple keys from same value in Python dictionary

Time:04-21

I want to get all the second-lowest numbers from this code. But if there is the same number more than once, I get only one.

Example:

input

{'m': 9, 'k': 8, 'l': 7, 'h': 8, 'i': 100} 

output

[100, 9, 8, 8, 7]  8 k 

required output

8 k   h

where would I change?

 n = int(input("enter a number:"))
d = {}

for i in range(n):
    keys = input() # here i have taken keys as strings
    values = int(input()) # here i have taken values as integers
    d[keys] = values
print(d)

t = d.values()
lst = list(t)
k= d.keys()
k_lst = list(k)
arr=sorted(lst,reverse=True)
print(arr)
mn=min(arr)
y=-788
for i in range(0,n):
    if arr[i]>mn:
        y = arr[i]
        
print(y)
position = lst.index(y)
print(k_lst[position])

CodePudding user response:

You can do it with this simple code:

second_lowest_value = sorted(set(d.values()))[1]
print(second_lowest_value, end=' ')
for key, value in d.items():
    if value == second_lowest_value:
        print(key, end=' ')

CodePudding user response:

You can do it even in one line, but I splited it so you can see what is happening.. Probably you don't even need the list() for the last line...

inp ={'m': 9, 'k': 8, 'l': 7, 'h': 8, 'i': 100}

second_low_val = sorted(set(inp.values()))[1]
res = list(filter(lambda x : x[1] == second_low_val, inp.items()))

## res:
# [('k', 8), ('h', 8)]

Then you can do with that list anything what you want...

  • Related