python - 如何首先按键按字母顺序对字典进行排序,然后按值升序排序?

标签 python sorting dictionary

我有一本字典,mydict,其形状如下:

{'qui': [(4, 1), (3, 2), (10, 1)], 'voluptate': [(3, 1)], 'est': [(4, 1)], 'reprehenderit': [(3, 1)], 'cillum': [(3, 1), (9, 1)], 'irure': [(1, 1), (3, 1)], 'laboris': [(2, 1)], 'sit': [(1, 1)], 'sunt': [(4, 1)], 'eu': [(3, 1)], 'nisi': [(5, 1), (2, 1)]}

我需要首先按字母顺序对键进行排序,然后完成后,按元组中的第一个数字对元组进行排序。

我看过用于排序的资源 first by key then value , sorting alphabetically ,和sorting by value then key ,但到目前为止还没有问题出现过这个问题。

我尝试过使用 sorted_dict = Sorted(d.keys()) 但这只是按字母顺序返回我的键列表,而不是它们的值

如何实现如下目标结果?:

{'cillum': [(3, 1), (9, 1)], 'est': [(4, 1)], 'eu': [(3, 1)], 'irure': [(1, 1), (3, 1)], 'laboris': [(2, 1)], 'nisi': [(2, 1), (5, 1)], 'qui': [(3, 2), (4, 1), (10, 1)], 'reprehenderit': [(3, 1)], 'sit': [(1, 1)], 'sunt': [(4, 1)], 'voluptate': [(3, 1)],}

python --version yields Python 3.6.7

最佳答案

正如 @DeepSpace 所指出的,OP 使用 Python 3.6。

因此,dicts order 是一个实现细节,我们必须使用 OrderedDict。

这是我的版本:

from collections import OrderedDict

d = {'qui': [(4, 1), (3, 2), (10, 1)], 'voluptate': [(3, 1)], 'est': [(4, 1)], 'reprehenderit': [(3, 1)], 'cillum': [(3, 1), (9, 1)], 'irure': [(1, 1), (3, 1)], 'laboris': [(2, 1)], 'sit': [(1, 1)], 'sunt': [(4, 1)], 'eu': [(3, 1)], 'nisi': [(5, 1), (2, 1)]}

ordered_dict = OrderedDict()
sorted_keys = sorted(d.keys())

for key in sorted_keys:
    sorted_values = sorted(d[key])
    ordered_dict[key] = sorted_values

print(ordered_dict)

输出:

OrderedDict([('cillum', [(3, 1), (9, 1)]), ('est', [(4, 1)]), ('eu', [(3, 1)]), ('irure', [(1, 1), (3, 1)]), ('laboris', [(2, 1)]), ('nisi', [(2, 1), (5, 1)]), ('qui', [(3, 2), (4, 1), (10, 1)]), ('reprehenderit', [(3, 1)]), ('sit', [(1, 1)]), ('sunt', [(4, 1)]), ('voluptate', [(3, 1)])])

关于python - 如何首先按键按字母顺序对字典进行排序,然后按值升序排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57975460/

相关文章:

java - 手动数组排序返回 nullpointerexception

algorithm - 将STL映射转换为基于数值的键排序列表的好算法

python - 对称字典,其中 d[a][b] == d[b][a]

linux - Linux 中的排序问题

java - 包含列表的 gwt RequestFactory 映射

python ImportError Openvino 通过脚本和 shell

python - 如何使用turtle.bgpic()返回图像

python - 本地主机拒绝在调用 google api 的 databricks 笔记本中连接

python - 如何在 pygame 的动画中添加 2 个以上的 Sprite ?

sorting - SublimeText - 按字母顺序对 json 列表进行排序