python - 对字典进行排序但出现 "List Indices must be int, not tuple"错误

标签 python sorting dictionary

我正在尝试使用 sorted() 函数,因为我无法使用 OrderedDict (python 2.6.6)。但是我得到这个“List indices must be int, not tuple”错误

我尝试只在字典上使用 sorted() 函数,当我尝试使用一些虚拟值时它工作正常,但我不确定为什么它不适用于我的特定代码。

   venue_dict = {}
   for venues in venue_names:
       venue_dict[venues] = False
   venue_dict = sorted(venue_dict)

我得到这个 TypeError: list indices must be integers, not str

所以我为每个地点创建了一个值为 False 的字典。 (venue_names 是所有 field 名称的列表) false 只是用作标志值。

无论如何,我尝试打印排序后的字典,但收到元组错误。 有人知道为什么吗?我试着用谷歌搜索这个,但还没有找到解决方案。

最佳答案

内置 sorted()函数不适用于具有默认参数的字典,因为默认排序键将是 (key, value) 对。这是一个元组,而不是一个可排序的项目。

您可以通过 lambda 函数确保将字典键用作排序键:

mydict = sorted(mydict, key=lambda k: k[0])  # just the key from the (key, value) tuple

或者,您可以直接对字典的项目进行排序:

mydict = sorted(mydict.items())

上面的语句将返回元组列表。如果你想要一个实际的有序字典,你将不得不使用 OrderedDict。由于您使用的是 Python 2.6,而这只是 Python 2.7 中的一个问题,因此您可以安装 ordereddict通过运行 pip install ordereddict 通过 PIP 打包。然后:

from ordereddict import OrderedDict

mydict = OrderedDict(sorted(mydict.items()))

关于python - 对字典进行排序但出现 "List Indices must be int, not tuple"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57013674/

相关文章:

python - 我可以传递 dask 数据帧作为 scikit-learn 模型的输入吗?

python - 如何将一周中的几天分成一周并对其执行函数

java - 什么更快 : Using Quicksort then Binary Search OR Just Linear Search?

java - 在 Java8 函数式风格中,我如何将值映射到已经存在的键值对

python - 将两个字典的信息翻译成字典列表

python - 如何通过 django Rest 框架使用数据表服务器端处理

python - 如何使用 cmp 将排序从 python 2 转换为 python 3?

jquery - 对下拉列表中不包含第一项的项目进行排序

python - 我可以像 python 中的字典引用一样对对象进行可变化吗

python - 如何禁用Python警告?