python - 似乎无法遍历键为数字字符串的已排序字典。您如何对字典进行排序以进行迭代?

标签 python sorting dictionary

我有这本字典 (dic),其中键是字符串,但字符串实际上只是数字。

我找不到迭代排序字符串的方法(因为字典排序不会按数字排序)

for j in sorted([int(k) for k in dic.iteritems()]):
    print dic[str(j)] #converting the integer back into a string for the key

它给了我

KeyError

凭直觉这应该可行,但我只是不明白为什么不行。

最佳答案

dict.iteritems() 返回二元组,不能转换成整数。

for j in sorted(dic, key=int):
    print dic[j]

关于python - 似乎无法遍历键为数字字符串的已排序字典。您如何对字典进行排序以进行迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36946649/

相关文章:

python - 如何: Overlapping match

python - Apple 会允许 iOS App Store 中使用 Python 中的 Kivi 框架吗?

java - 如何根据项目的主序列列表对一小部分项目进行排序?

sorting - 如何在Lua中按 "score"然后 "index"对内表进行排序?

algorithm - 打印向量的所有排列

python - 字典只返回 for 循环中的最后一个键值对

python - 字典中的最大键值

python - 绘图中的多个系列

python - Python 中的内容查看检查

python - 在字典中检查多个 if 条件的优雅方法