我有一本字典,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/