我有这本字典 (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/