Python 嵌套字典和字符串索引错误
谢谢你抽出时间来帮助我。我有下面的代码,我一辈子都不明白为什么它不起作用。请原谅,我只是在过去的两周左右才开始使用Python,所以我肯定我把事情搞砸了Python 嵌套字典和字符串索引错误,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,谢谢你抽出时间来帮助我。我有下面的代码,我一辈子都不明白为什么它不起作用。请原谅,我只是在过去的两周左右才开始使用Python,所以我肯定我把事情搞砸了 import os import plistlib pl = {1:{11:'k','Letters':'qrst',13:'m'}, 2:{11:'k','Letters':'lmn',13:'m'}, 3:'c', 4:'d', 5:'e'} for left, right in p
import os
import plistlib
pl = {1:{11:'k','Letters':'qrst',13:'m'},
2:{11:'k','Letters':'lmn',13:'m'},
3:'c',
4:'d',
5:'e'}
for left, right in pl.items():
for values in right.values():
print(values['Letters'])
当我运行此操作时,会出现以下错误:
Traceback (most recent call last):
File "plist.py", line 34, in <module>
print(values['Letters'])
TypeError: string indices must be integers
回溯(最近一次呼叫最后一次):
文件“plist.py”,第34行,在
打印(值['字母])
TypeError:字符串索引必须是整数
我的目标是回归:
qrst
lmn
多谢各位 要访问内部字典键,不需要迭代。您可以使用
dict.\uuu getitem\uuu
或dict.get
。但是,由于外部字典值不是所有的字典,因此您需要执行一些类型检查,或者使用try
/,但除外
以下是后一种方法的示例:
for left, right in pl.items():
try:
print(right['Letters'])
except TypeError:
pass
qrst
lmn
祝你一切顺利。继续发布更具挑战性的问题。快乐学习
for k,v in pl.items():
if type(v)==dict:
print(v["Letters"])
else:
continue