An example of my data structure looks like this:
main list :
[{..}, {..}, ..] # list of dictionaries
main list stores list element dicts :
{
'queues': [{..}, {..}, ..], # list of more dictionaries
}
inner list element dict :
{
'member': ["string", "string", ..] # list of strings
}
My goal is to sort main list based on the length of the member list in the inner dictionaries. What's an efficient and pythonic way to accomplish this?
You can use either sorted
or list.sort
with an appropriate key function. If you sort by the total length of all member
lists:
main_list.sort(key=lambda d: sum(len(x['member']) for x in d['queues']))
Or if you want to always consider only the first one relevant:
main_list.sort(key=lambda d: len(d['queues'][0]['member']))
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.