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!

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
King
  • 87
  • 1
  • 9
  • 1
    `test.sort(key=lambda x: x['password'] != 'test3')` – StardustGogeta Aug 01 '19 at 19:45
  • 1
    So the dict(s) with `d['password'] == 'test3'` has to come first, with the remaining dicts in any arbitrary order? – chepner Aug 01 '19 at 19:45
  • @chepner Yes exactly – King Aug 01 '19 at 19:49
  • @StardustGogeta that works! Thank you! – King Aug 01 '19 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.) – chepner Aug 01 '19 at 19:53
  • @King your question is incomplete. In a set of items an order must be defined among all items. In your example however, The only order you point out is `test3` and all the other items. I recommend to explain more about the expected outcome. The question as it stands simply does not make sense. – Ely Aug 01 '19 at 19:59

1 Answers1

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'.

chepner
  • 497,756
  • 71
  • 530
  • 681
StardustGogeta
  • 3,331
  • 2
  • 18
  • 32