Home > Enterprise >  Python- remove the item with lowest value, if two values are the same remove item with lowest key
Python- remove the item with lowest value, if two values are the same remove item with lowest key

Time:11-05

So i have a dictionary that has keys (ints), and values (also ints). I want to delete the item from the dictionary if the value is the smallest, but if there are two items that have the same values I want to delete the item that has the smallest key.

So far, I have managed to select the minimum value using min_key = min(dictionary, key=dictionary.get) but if there is more than one item with the same value it will just select the first value in the dictionary it finds, not both of them.

Does anyone have any suggestions?

CodePudding user response:

You can use lambda with two conditions as the key in min

min_key = min(dictionary, key=lambda k: (dictionary.get(k), k))

this will find the smallest value first and then the smallest key if there is more than on match.

dictionary = {4: 1, 5: 1, 3: 3, 0: 4} # will give 4
dictionary = {4: 1, 2: 1, 3: 3, 0: 4} # will give 2

CodePudding user response:

Seperate values and keys. First create a list of values and find minimum using min() function. Then using loop, check for all keys which have least value and collect it in a list. Then find min of key using min() function again. Your code:

x={1:4,2:4,5:1,6:1}
m1=min(list(x.values()))
m2=[]              #m2 for collecting keys which have least value
for i in x:
    if x[i]==m1:
        m2.append(i)      #appending

del x[min(m2)]
print(x)

output:

{1:4,2:4,6:1}
  • Related