简体   繁体   中英

How to sort default dict with list values in python

I have a defaultdict with list as

defaultdict(<class 'list'>, {'SOL200122': ['125', '135', '145', '170', '120', '130', '140', '150', '160']}

I want it to be sorted like

defaultdict(<class 'list'>, {'SOL200122': ['120', '125', '130', '135', '140', '145', '150', '160', '170']}

Have tried

sorted(myDict.items(), key=lambda k_v: (k_v[1][2]), reverse=True)

But not working

Use list.sort with key=int (thanks @Metapod, @deceze et al):

for v in d.values():
    v.sort(key=int)

If you want a one-liner (which makes no sense in this case because for-loop is very nice), a monstrosity like this one could be one I guess:

dict(zip(d.keys(), map(lambda x: sorted(x, key=int), d.values())))

Output:

{'SOL200122': ['120', '125', '130', '135', '140', '145', '150', '160', '170']}

try this:

for v in d.values():
    v.sort(key=int)

output:

{'SOL200122': ['120', '125', '130', '135', '140', '145', '150', '160', '170']}

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