Home > Back-end >  Finding the lowest value or fewest items in a python dictionary that has lists as values
Finding the lowest value or fewest items in a python dictionary that has lists as values

Time:07-16

I have a dictionary with lists as values ; i need to find the key which has the fewer number of items in its list

Also I need to find what key has the item in the list with the lowest individual score.

I've really got no idea how to approach the first problem but my attempts to find the 2nd I feel like my coding attempts are not bringing back the results I would expect.

Thanks for any help or any pointers


results = {
    'a': [21, 23, 24, 19],
    'b': [16, 15, 12, 19],
    'c': [23, 22, 23],
    'd': [18, 20, 26, 24],
    'e': [17, 22],
    'f': [22, 24],
    'g': [21, 21, 28, 25]
}



#Attempt1
print(min(results.items()))

#attempt2
print(results[min(results,key=results.get)])

CodePudding user response:

You can use:

Fewest items:

min(results, key=lambda x: len(results[x]))

output: 'e'

Lowest min score:

min(results, key=lambda x: min(results[x]))

output: 'b'

why your attempts failed:

min(results.items())

would get the lowest key first, then in case of a tie compare the lists (Note that there cannot be a tie as keys are unique). So, this would be the same as min(results.keys())

min(results, key=results.get)

would compare the values, and pick the one with the smallest first item in the list, or second in case of a tie, or third…

CodePudding user response:

Try below for key that has lower len:

>>> min(results, key=lambda x: len(results[x]))
'e'

try below for key that have lower value:

>>> min(results, key=lambda x: min(results[x]))
'b'

How does this work?

min(results, key=lambda x: ...)
# ---------------------^^^ x is a key of your dict : 'a', 'b', ...
# Then when write min(results[x]) or len(results[x]), we want to find 
min(min(results['a']) , min(results['b']), ...))
min(results, key = 19, 12, ...)
----------------^'a'^,^'b'^
# So when 12 is min, we get key 'b'
  • Related