Home > database >  Find the shortest value in a list of dictionaries
Find the shortest value in a list of dictionaries

Time:03-24

I have a list like this one:

players = [
    {
      'name': 'jowick42',
      'stack': [[1, 3], [1, 3], [1, 3]]
    },
    {
      'name': 'robot',
      'stack': [[2, 3], [2, 3], [2, 3]]
    }
  ]

I want to automatically find the shortest value of 'name' between the two names. In this case robot should be what is found. Whether the shortest name is in the first dict or in the second one doesn't matter.

I don't know how to do this which is why I'm asking here.

CodePudding user response:

One method is to use the min function

player = min(players, key=lambda player: len(player['name']))
print (player['name'])

CodePudding user response:

You can do it via list comprehension, then sorting:

# extract names via list comprehension
names = [player["name"] for player in players]

# sort names, and get the last item to get the smallest one
print(sorted(names)[-1])
  • Related