如何按键对字典进行排序?
示例输入:
{2:3, 1:89, 4:5, 3:0}
期望的输出:
{1:89, 2:3, 3:0, 4:5}
如何按键对字典进行排序?
示例输入:
{2:3, 1:89, 4:5, 3:0}
期望的输出:
{1:89, 2:3, 3:0, 4:5}
当前回答
我认为最简单的事情是按键对字典进行排序,并将排序的键:值对保存在一个新的字典中。
dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2}
dict2 = {} # create an empty dict to store the sorted values
for key in sorted(dict1.keys()):
if not key in dict2: # Depending on the goal, this line may not be neccessary
dict2[key] = dict1[key]
更清楚地说:
dict1 = {'renault': 3, 'ford':4, 'volvo': 1, 'toyota': 2}
dict2 = {} # create an empty dict to store the sorted values
for key in sorted(dict1.keys()):
if not key in dict2: # Depending on the goal, this line may not be neccessary
value = dict1[key]
dict2[key] = value
其他回答
找到了另一种方法:
import json
print json.dumps(d, sort_keys = True)
乌利希期刊指南: 1. 这也可以对嵌套对象进行排序(谢谢@DanielF)。 2. Python字典是无序的,因此只适用于打印或赋值给STR。
您可以根据您的问题按键对当前字典进行排序,从而创建一个新字典。
这是你的字典
d = {2:3, 1:89, 4:5, 3:0}
通过使用lambda函数对这个d排序,创建一个新字典d1
d1 = dict(sorted(d.items(), key = lambda x:x[0]))
D1应为{1:89,2:3,3:0,4:5},根据d中的键进行排序。
我想出了单行字典排序。
>> a = {2:3, 1:89, 4:5, 3:0}
>> c = {i:a[i] for i in sorted(a.keys())}
>> print(c)
{1: 89, 2: 3, 3: 0, 4: 5}
[Finished in 0.4s]
希望这对你有所帮助。
Python字典在Python 3.6之前是无序的。在Python 3.6的CPython实现中,字典保持插入顺序。 从Python 3.7开始,这将成为一种语言特性。
在Python 3.6的更新日志(https://docs.python.org/3.6/whatsnew/3.6.html#whatsnew36-compactdict):
考虑了这个新实现的保序方面 一个实现细节,不应该依赖(这可能 将来会有变化,但希望有这个新词典 在语言中实现了几个版本,然后才更改 语言规范要求所有当前的语义保持有序 以及未来的Python实现;这也有助于保存 向后兼容该语言的旧版本 随机迭代顺序仍然有效,例如Python 3.5)。
Python 3.7文档(https://docs.python.org/3.7/tutorial/datastructures.html#dictionaries):
在字典上执行list(d)将返回所有使用的键的列表 在字典中,按插入顺序(如果你想排序,只需使用 排序(d))。
因此,与以前的版本不同,您可以在Python 3.6/3.7之后对字典进行排序。如果你想对包含子字典在内的嵌套字典进行排序,你可以这样做:
test_dict = {'a': 1, 'c': 3, 'b': {'b2': 2, 'b1': 1}}
def dict_reorder(item):
return {k: dict_reoder(v) if isinstance(v, dict) else v for k, v in sorted(item.items())}
reordered_dict = dict_reorder(test_dict)
https://gist.github.com/ligyxy/f60f0374defc383aa098d44cfbd318eb
就问题的表述方式而言,这里的大多数答案都是正确的。
然而,考虑到事情应该如何真正完成,考虑到几十年的计算机科学,让我完全惊讶的是,这里实际上只有一个答案(来自GrantJ用户)建议使用排序关联容器(sortedcontainers),它基于插入点的键对元素进行排序。
这将避免每次调用sort(…)时对性能的巨大影响(至少O(N*log(N)),其中N是元素的数量(逻辑上,这适用于这里建议使用sort(…)的所有此类解决方案)。考虑到对于所有这样的解决方案,sort(…)将需要在每次通过添加/删除元素修改后,当需要以排序方式访问集合时调用…