遍历嵌套字典列表
Iterating over a list of nested dictionaries
您好,我正在尝试遍历此列表并访问嵌套字典中的特定值
[{'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
[d for d in Account.accountList if d.customer.name == 'smith']
你很接近
问题就在这里
def __getitem__(self, i):
return i
你可以看看下面发生了什么
MyClass["whatever"] == "whatever" #True
"whatever"["asd"] #error
相反,我认为你可以使用
def __getitem__(self,item):
return getattr(self,item)
你正在尝试的实际上对我有用!
输入:
details = [{'customer': {'name': 'Karl'}}, {'customer': {'name': 'Smith'}}]
[x for x in details if x['customer']['name'] == 'Smith']
结果:
[{'customer': {'name': 'Smith'}}]
编辑:
仔细看这条线...
Account.accountList.append(self)
您似乎将一个对象附加到 AccountList
而不是您期望的字典,因为 self
是一个对象。尝试:
Account.accountList.append({'customer': {'name': name}})
您好,我正在尝试遍历此列表并访问嵌套字典中的特定值
[{'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
[d for d in Account.accountList if d.customer.name == 'smith']
你很接近
问题就在这里
def __getitem__(self, i):
return i
你可以看看下面发生了什么
MyClass["whatever"] == "whatever" #True
"whatever"["asd"] #error
相反,我认为你可以使用
def __getitem__(self,item):
return getattr(self,item)
你正在尝试的实际上对我有用!
输入:
details = [{'customer': {'name': 'Karl'}}, {'customer': {'name': 'Smith'}}]
[x for x in details if x['customer']['name'] == 'Smith']
结果:
[{'customer': {'name': 'Smith'}}]
编辑:
仔细看这条线...
Account.accountList.append(self)
您似乎将一个对象附加到 AccountList
而不是您期望的字典,因为 self
是一个对象。尝试:
Account.accountList.append({'customer': {'name': name}})