0

I am having trouble trying to sort a list of dictionaries based on a value matching a string. Here's an example:

test = [{'username': "1", "password": "test1"},
        {"username": "3", "password": "test2"},
        {"username": "5", "password": "test3"}]

I would like to sort this dictionary based on password = test3, so it would look like:

test = [{"username": "5", "password": "test3"},
        {'username': "1", "password": "test1"},
        {"username": "3", "password": "test2"}]

Any help would be appreciated. Thank you!

6
  • 1
    test.sort(key=lambda x: x['password'] != 'test3') Commented Aug 1, 2019 at 19:45
  • 1
    So the dict(s) with d['password'] == 'test3' has to come first, with the remaining dicts in any arbitrary order? Commented Aug 1, 2019 at 19:45
  • @chepner Yes exactly Commented Aug 1, 2019 at 19:49
  • @StardustGogeta that works! Thank you! Commented Aug 1, 2019 at 19:50
  • Not really a duplicate, since we're sorting on a value derived from the value, not the value itself. (There may be a better duplicate, though.) Commented Aug 1, 2019 at 19:53

1 Answer 1

2
test.sort(key=lambda x: x['password'] != 'test3')

The .sort() method for lists allows you to use an arbitrary key function. In this case, we use a function that returns False (which equals 0) if the 'password' field equals 'test3'.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.