简体   繁体   中英

Sorting a list of dictionaries based on a value

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM