简体   繁体   中英

Sort a list of dicts by multiple items AND different reverse values for each item

I have the following list of objects and I want to sort them such that first all dicts with k2 == True (alphabetically ordered AZ) and afterwards all dicts with k2 == False (alphabetically ordered AZ). I tried something like this sorted(test, key=lambda k: (k['k2'], k['k1'].lower()), reverse=(True,False)) but it doesn't work.

>>> test = [
...     {"k1": "qsd", "k2": True},
...     {"k1": "JKd", "k2": False},
...     {"k1": "Ukz", "k2": False},
...     {"k1": "aqd", "k2": True},
...     {"k1": "Asd", "k2": True},
...     {"k1": "wef", "k2": False},
...     {"k1": "Wgr", "k2": True},
...     {"k1": "weg", "k2": False},
...     {"k1": "lfe", "k2": True},
... ]
>>>
>>> test = sorted(test, key=lambda k: (k['k2'], k['k1'].lower()), reverse=True)
>>> for t in test:
...     print(t)
...
{'k1': 'Wgr', 'k2': True}
{'k1': 'qsd', 'k2': True}
{'k1': 'lfe', 'k2': True}
{'k1': 'Asd', 'k2': True}
{'k1': 'aqd', 'k2': True}
{'k1': 'weg', 'k2': False}
{'k1': 'wef', 'k2': False}
{'k1': 'Ukz', 'k2': False}
{'k1': 'JKd', 'k2': False}

I'm looking for:

{'k1': 'aqd', 'k2': True}
{'k1': 'Asd', 'k2': True}
{'k1': 'lfe', 'k2': True}
{'k1': 'qsd', 'k2': True}
{'k1': 'Wgr', 'k2': True}
{'k1': 'JKd', 'k2': False}
{'k1': 'Ukz', 'k2': False}
{'k1': 'wef', 'k2': False}
{'k1': 'weg', 'k2': False}

You're close, use not k['k2'] for the first sorter.

>>> test.sort(key=lambda k: (not k['k2'], k['k1'].lower()))
>>> test
[{'k1': 'aqd', 'k2': True},
 {'k1': 'Asd', 'k2': True},
 {'k1': 'lfe', 'k2': True},
 {'k1': 'qsd', 'k2': True},
 {'k1': 'Wgr', 'k2': True},
 {'k1': 'JKd', 'k2': False},
 {'k1': 'Ukz', 'k2': False},
 {'k1': 'wef', 'k2': False},
 {'k1': 'weg', 'k2': False}]

not k['k2'] is False when k['k2'] is True, and False (=0) < True (=1).

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