How to put condition in python lambda function

Question:

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]))
Asked By: Prem

||

Answers:

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 :).

Answered By: cucurbit
max_user_id = max(res, key=lambda x:int(re.split(r"^user(d+).*$", x['Username'])[1]) if len(re.split(r"^user(d+).*$", x['Username'])) > 1 else 0)

Messy but can be used

Answered By: Rahul Beniwal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.