在 Python 中循环字典时遇到问题

Having trouble to loop through dictionaries in Python

我正在学习 Python,但我在遍历词典时遇到了一些问题。我想遍历整个字典并使用以下代码打印每个值:

d = {"Room" : 100, "Day" : 25, "Night" : 88}

for key in d:
    print d[key]

但是得到一个错误信息:

Traceback (most recent call last):
  File "python", line 9, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 18: ordinal not in range(128)

您在代码中加入了无效字符。 Python2 默认使用 ascii 编码,因此它不允许超过 127 个字符(0xc3 == 195 是)。由于这看起来像是一个错误,请删除整个有问题的行并重新输入它——您的代码片段在这里工作得很好。

您也可以将编码设置为 utf-8,这样应该可以消除错误。但是你应该避免这个修复,因为它似乎不适合这种情况:

# top of the file
import sys
sys.setdefaultencoding('utf8')

初始答案,在实际错误之前:

您使用的是 Python 版本 3+,它改变了 print 的语义。它现在是一个函数,所以按照错误提示使用 print(somevalue).

Python2:

>>> for key in d:
...     print d[key]
... 
88
100
25
>>> type(print)
  File "<stdin>", line 1
    type(print)
             ^
SyntaxError: invalid syntax

Python3:

>>> for key in d:
...     print d[key]
  File "<stdin>", line 2
    print d[key]
          ^
SyntaxError: Missing parentheses in call to 'print'
>>> type(print)
<class 'builtin_function_or_method'>

查看 Python dict 文档。如果你想遍历值:

for value in d.values():
    print(value)

您可以使用:

d = {"Room" : 100, "Day" : 25, "Night" : 88}

for key, value in d.items():
     print key, value

简单地说,这是当我 运行 你的代码时 sublime 问我的: 您是说 print(d[key]) 吗? :-)

您还可以使用:

d = {"Room" : 100, "Day" : 25, "Night" : 88}
for key in d:
    v = d[key]
    print(v)

必要时的解释: 对于 'd' 字典中的每个元素: 创建名为 'v' 的变量,分配给 d / 中的每个元素 打印变量 v