简体   繁体   中英

how to sort a dictionary by key first then by tuple values

Given an input dictionary like

{13: (3,1,7), 2: (6,4,9), 7: (5,8,4)}

get an out put dictionary like

{2: (4,6,9), 7: (4,5,8), 13: (1,3,7)}

From Python 3.6 onwards, dictionaries honor insertion order. You can accomplish what you want by using sorted at the level of both the dict items as well as within the individual values:

>>> dict(sorted((k, tuple(sorted(v))) for (k, v) in a.items()))
{2: (4, 6, 9), 7: (4, 5, 8), 13: (1, 3, 7)}

You can use comprehension.

a = {13: (3,1,7), 2: (6,4,9), 7: (5,8,4)}
sorted_a = {key:tuple(sorted(a[key])) for key in sorted(a)}

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