[英]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 output
[100, 9, 8, 8, 7] 8 k
required output必填 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...你甚至可以在一行中完成,但我把它分开了,这样你就可以看到发生了什么。可能你甚至不需要最后一行的 list() ......
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...然后你可以用这个列表做任何你想做的事......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.