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

Time:05-29

I would like to find min and max of dictionary where 2 or more keys have the same value.

The following dict:

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

At the end I would like to print sth like that:

"5 and 6- max values" "0 and 2 and 4- min values"

This is what I've tried:

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

CodePudding user response:

Here's a way to do what your question asks:

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

Output:

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

CodePudding user response:

You could extract the values and get the min/max, and then get the items and filter by those values:

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]}")
  • Related