Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sorting 根据键按升序对python中的词典排序_Sorting_Dictionary - Fatal编程技术网

Sorting 根据键按升序对python中的词典排序

Sorting 根据键按升序对python中的词典排序,sorting,dictionary,Sorting,Dictionary,我有一本字典: 我正在使用内置函数对字典目录进行排序(已排序(d.items()) 我希望我的输出类似于: {'0':'0','1':'0','2':'0','3':'1245','4':.......} 但现在键的顺序是0,1,10100 我想要1,2,3,4 d={'113': '5', '114': '305', '115': '50', '116': '0', '117': '0', '118': '0', '119': '0', '12': '1245', '120': '0', '

我有一本字典:

我正在使用内置函数对字典目录进行排序(已排序(d.items())

我希望我的输出类似于:

{'0':'0','1':'0','2':'0','3':'1245','4':.......}
但现在键的顺序是0,1,10100

我想要1,2,3,4

d={'113': '5', '114': '305', '115': '50', '116': '0', '117': '0', '118': '0', '119': '0', '12': '1245', '120': '0', '121': '0', '122': '10', '123': '10', '124': '0', '125': '0', '126': '0', '127': '0', '128': '0', '129': '610,'0': '0', '1': '0', '10': '0', '100': '0', '101': '0', '102': '0', '103': '0', '108': '0', '109': '194', '11': '0', '110': '340', '111': '0', '112': '10', '', '13': '0', '130': '20','104': '120', '105': '105', '106': '0', '107': '0'}

print(dict(sorted(d.items())))
输出如下所示

{'0': '0', '1': '0', '10': '0', '100': '0', '101': '0', '102': '0', '103': '0', '104': '120', '105': '105', '106': '0', '107': '0', '108': '0', '109': '194', '11': '0', '110': '340', '111': '0', '112': '10', '113': '5', '114': '305', '115': '50', '116': '0', '117': '0', '118': '0', '119': '0', '12': '1245', '120': '0', '121': '0', '122': '10', '123': '10', '124': '0', '125': '0', '126': '0', '127': '0', '128': '0', '129': '610', '13': '0', '130': '20'}

请帮助我使用正确的方法以这种方式对其进行排序。

因为您希望对已排序的词典使用基于零的索引,下面的解决方案应该适用于您的用例

a = dict(sorted(d.items()))
res = {}
ctr=0
for i in a.keys():
  res[ctr] = a[i]
  ctr+=1

print(res)

如果要对项目进行排序,则不能在之后将其保存在词典中。字典不能维持秩序

这将以排序列表的形式为您提供输出:

sorted(d.items(), key=lambda x: int(x[0]))

您可以使用OrderedDict

from collections import OrderedDict
d = OrderedDict(d)

键,键的顺序应该是:0,1,2,3,4..字典中的键和值都是字符串。你确定你送的字典是对的吗?你的字典值是整数还是字符串?是的,它应该是字符串