如何查找字典的最小值和最大值,其中 2 个或多个键具有相同的值

How to find min and max of dictionary where 2 or more keys have the same value

我想找到字典的最小值和最大值,其中 2 个或更多键具有相同的值。

下面的字典:

{0: 110001,
 1: 123716,
 2: 110001,
 3: 123349,
 4: 110001,
 5: 140000,
 6: 140000,
 7: 123601,
 8: 122691,
 9: 123767}

最后我想打印这样的东西:

“5 和 6- 最大值” “0、2 和 4- 最小值”

这是我试过的:

print("Min value occurs for: ", min(dict_counter, key=dict_counter.get))

这里有一种方法可以完成您的问题:

d = {0: 110001,
 1: 123716,
 2: 110001,
 3: 123349,
 4: 110001,
 5: 140000,
 6: 140000,
 7: 123601,
 8: 122691,
 9: 123767}
dMax, dMin = max(d.values()), min(d.values())
print(f"Min value occurs for: {[k for k, v in d.items() if v == dMin]}, Max value occurs for: {[k for k, v in d.items() if v == dMax]}")

输出:

Min value occurs for: [0, 2, 4], Max value occurs for: [5, 6]

您可以提取值并获取 min/max,然后获取项目并按这些值过滤:

d = {0: 110001, 1: 123716, 2: 110001,3: 123349, 4: 110001, 5: 140000, 6: 140000, 7: 123601, 8: 122691, 9: 123767}

low = min(d.values())
high = max(d.values())
print(f"low {low} found in {[k for k, v in d.items() if v == low]}")
print(f"high {high} found in {[k for k, v in d.items() if v == high]}")