简体   繁体   中英

How to get multiple keys from same value in Python dictionary

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])

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=' ')

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...

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