【发布时间】:2020-05-25 20:07:57
【问题描述】:
我有一本字典如下:
{1: 3, 2: 4, 3: 5, 4: 1, 5: 2}
我想重新排列它,使当前对的值是下对的键,像这样:
{1: 3, 3: 5, 5: 2, 2: 4, 4: 1}
我该如何处理?
【问题讨论】:
-
据我记得,python dict 没有指定为有序的,因此键值对中没有排序。您在打印字典时看到的顺序是任意的。编辑:这似乎是这种情况now :) 我认为您必须创建一个新字典并从一开始就以正确的顺序插入键,因为我认为它们不可重新排序。
-
看看OrderedDict结构类型:pymotw.com/3/collections/ordereddict.html
-
实际上,从 Python 3.6 开始,dictionaries are ordered by insertion order
标签: python python-3.x sorting dictionary key