简体   繁体   English

如何先按键然后按元组值对字典进行排序

[英]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.从 Python 3.6 开始,字典遵循插入顺序。 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来完成您想要的操作:

>>> 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)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM