Home > Net >  How do I choose multiple minimum values in a dictionary?
How do I choose multiple minimum values in a dictionary?

Time:03-21

I'm trying to inspect and choose values in a dictionary if they're the same minimum values from the whole dictionary.

As you can see, my code is choosing duplicate values although they're not the minimum values. How do i correct this error? For example, my code shouldn't't delete values (including duplicates) unless there are multiple '7.14'

     def tieBreaker (preDictionary):
        while True:
            minValues = min(preDictionary.values())
            minKeys = [k for k in preDictionary if preDictionary[k] == minValues]
            print(minKeys)

            for i in range(0, len(minKeys)):
                for j in range(0, len(minKeys)):

                    if minKeys[i] > minKeys[j]:
                        del preDictionary[minKeys[i]]
                        i  = 1
                        j  = 1

            if len(minKeys) < 2:

                return preDictionary
                break

Current output is {'candidate1': '35.71', 'candidate2': '28.57', 'candidate4': '14.29', 'candidate3': '7.14'}

While the input is {'candidate1': '35.71', 'candidate2': '28.57', 'candidate5': '14.29', 'candidate4': '14.29', 'candidate3': '7.14'}

candidate 5 should not be deleted as although it's a duplicate value, not a minimum..

Also, minKeys currently is ['candidate5', 'candidate4'] where it should be ['candidate3']

CodePudding user response:

You do not need a while loop. You can run through each key value pair and construct a new dict without the keys with minimum value.

d = {'candidate1': 35.71, 'candidate2': 28.57, 'candidate4': 14.29, 'candidate3': 7.14}
min_value = min(d.values())

d_without_min_value = {k: v for k, v in d.items() if v != min_value}

# output
# {'candidate1': 35.71, 'candidate2': 28.57, 'candidate4': 14.29}

EDIT

Seems like you are passing values as string instead of float. Calling min() on a list of str will result in minimum value in lexicographical order. Remove the quotes around the values or convert the values into float before you process the dict

d = {k: float(v) for k, v in d.items()}
  • Related