如何使用enumerate对python中的词典进行排序?

如何使用enumerate对python中的词典进行排序?,python,dictionary,enumerate,sorteddictionary,Python,Dictionary,Enumerate,Sorteddictionary,我有以下代码 for index,(key,value) in enumerate(dict_var.items()): sorted_dict[index] = (key, value) print("The sorted list is:{}".format(sorted_dict)) 在哪里 dict_var是一本字典 sorted_dict是一个按排序顺序存储dict_var的键和值的列表 有人能解释为什么这个代码不起作用吗 我得到这个错误: 已排序的目录[索引]=(键、

我有以下代码

for index,(key,value) in enumerate(dict_var.items()):
    sorted_dict[index] = (key, value)

print("The sorted list is:{}".format(sorted_dict))
在哪里

  • dict_var是一本字典
  • sorted_dict是一个按排序顺序存储dict_var的键和值的列表
有人能解释为什么这个代码不起作用吗

我得到这个错误:

已排序的目录[索引]=(键、值)
索引器:列表分配索引超出范围


您得到索引错误是因为
dict\u var
的len大于
sorted\u dict
的len。为避免此错误,请确保列表的大小大于或与排序的目录的长度相同。如果您能在运行代码之前向我们展示排序后的dict的样子,这也会有所帮助。此外,给列表命名可能不是一个好主意。
sorted\u dict
<代码>排序列表会更好。您还可以通过以下方法避免此错误:

for key, value in dict_var.items():
    sorted_dict.append((key, value))
该索引专门用于访问python列表中的现有位置,并且不会自动创建列表以容纳超出范围的索引。这个问题与枚举无关

您可以简单地使用列表的.append()在末尾添加项。 例如:

sorted_dict = []
for key,value in dict_var.items():
    sorted_dict.append((key, value))

print("The sorted list is:{}".format(sorted_dict))

为什么要使用enumerate的可能重复项?它只会生成字典中已经存在的排序,而不会对任何内容进行排序。您可以使用
sorted(dict\u var.items())
生成已排序项目的列表。您还可以将已排序的dict视为dict,而不是列表。
sorted_dict = []
for key,value in dict_var.items():
    sorted_dict.append((key, value))

print("The sorted list is:{}".format(sorted_dict))