【发布时间】:2015-12-06 01:33:51
【问题描述】:
您好,我正在尝试遍历此列表并访问嵌套字典中的特定值
[{'customer': {'name': 'Karl'}}, {'customer': {'name': 'Smith'}}]
使用这个列表理解
[d for d in Account.accountList if d['customer']['name'] == 'smith']
但我得到了这个TypeError: string indices must be integers,我知道这与 python 认为我的列表是一个字符串有关,但它绝对是一个列表
>>> type(Account.accountList)
<class 'list'>
我尝试过嵌套 for 循环,但我不断收到此错误,不胜感激。..
class Customer:
def __init__(self, name):
self.name = name
def __repr__(self):
return repr(self.__dict__)
class Account:
accountList = []
def __init__(self, name):
self.customer = Customer(name)
Account.accountList.append(self)
def __repr__(self):
return repr(self.__dict__)
def __getitem__(self, i):
return i
【问题讨论】:
-
那些不是字典...
标签: python dictionary nested