简体   繁体   中英

sort nested dict

I have a dict in python

data={'d':{'2022-01-04':'completed'},'b':{'2020-12-04':'not competed'}}

I'd like to sort this list by date so the result should look like this

data={'b':{'2020-12-04':'not competed'},'d':{'2022-01-04':'completed'}}

tried

{i:sorted(data[i].items(), key=lambda x: x[0]) for i in data} 

but it only sort sub dict, any idea how to do this?

It's quite ugly, but the following seems to work:

data={'d': {'2022-01-04': 'completed'},
      'b': {'2020-12-04': 'not competed'}}

data = dict(sorted(data.items(), key=lambda pair: next(iter(pair[1]))))
list(pair[1].keys())[0]))
print(data)

Output:

{'b': {'2020-12-04': 'not competed'}, 'd': {'2022-01-04': 'completed'}}

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