我收到一个奇怪的关键错误与Python字典。我的密钥是“B19013_001E”,我用dict“属性”命名了我的字典“sf_tracts”。这里是我的代码:Python关键错误与_
x = "B19013_001E"
for tract in sf_tracts:
print tract["properties"][x]
有了这个,我得到一个KeyError异常: “B19013_001E”
但是如果我更改代码这一点,价值观得到印刷:
x = "B19013_001E"
for tract in sf_tracts:
for key in tract["properties"]:
if key == "B19013_001E":
print tract["properties"][x]
有什么区别?
-edit- 我相信问题是下划线,因为其他键可以打印。我如何访问此密钥?
感谢
'sf_tracts'究竟是什么 – depperm
字符串中的下划线没有什么特别之处。 'print list(tract ['properties'])'产生了什么?你能分享一个密钥的确切引用表示吗? –
你在'sf_tracts'中有**多个**字典。不*所有*这些字典都有这个关键。你的字典循环中的''键可以用'if x in tract [“properties”]替换:print tract [“properties”] [x]',顺便说一句,不需要循环。 –