简体   繁体   中英

How to sort dictionary with list values?

How to sort the below dictionary?

dict_val = {"A": ["2", "1"], "B": ["6", "4"]}

Output:

{"A": ["1", "2"], "B": ["4", "6"]}

I'm guessing that we'd be having int in our lists, which in that case,

dict_val = {"A": ["2", "1"], "B": ["6", "4"]}

for k,v in dict_val.items():
    dict_val[k].sort(key=int)

might be just one way to do so.

Using sorted would be another option:

for k,v in dict_val.items():
    dict_val[k]=sorted(dict_val[k])

Output

{'A': ['1', '2'], 'B': ['4', '6']}

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