Search code examples
pythonlambda

How to put condition in python lambda function


I want to get the username with max suffix. So, the output for the res should be user0002. I want to ignore if the Username doesn't contain prefix user (this data actually throws exception). How to put the condition in lambda function to ignore the prefix other than user.

res = [{ "Username": "user0001"},{ "Username": "user0002"} {"Username": "test"}]
max_user_id = max(res, key=lambda x:int(x['Username'].split("user")[1]))

Solution

  • Try this:

    max([value for entry in res for value in entry.values() if value.startswith("user")])
    

    I personally don't like this long list of comprehensions, but this does what you want, and maybe you can take it from here :).