嵌套字典和字符串索引

2024-05-16 03:03:02 发布

您现在位置:Python中文网/ 问答频道 /正文

谢谢你抽出时间来帮我。我有下面的代码,我一辈子都搞不明白为什么它不起作用。请原谅我,我只在过去的两个星期左右的时间里和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 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

我的目标是回报: qrst公司 lmn公司

非常感谢


Tags: 代码inimportrightforos时间公司
2条回答
for k,v in pl.items():
   if type(v)==dict:
      print(v["Letters"])
   else:
      continue

要访问内部字典键,不需要迭代。您可以使用dict.__getitem__dict.get。但是,由于您的外部字典值不是所有的字典,因此您需要执行一些类型检查或使用try/except

下面是后一种方法的示例:

for left, right in pl.items():
    try:
        print(right['Letters'])
    except TypeError:
        pass

qrst
lmn

相关问题 更多 >