Python 迭代嵌套字典列表

Python 迭代嵌套字典列表,python,dictionary,nested,Python,Dictionary,Nested,您好,我正在尝试循环此列表并访问嵌套字典中的特定值 [{'customer':{'name':'Karl'},{'customer':{'name':'Smith'}}] 使用此列表理解 [d for d in Account.accountList if d['customer']['name'] == 'smith'] 但我得到了这个类型错误:字符串索引必须是整数,我知道这与python认为我的列表是字符串有关,但它确实是一个列表 >>> type(Account.acc

您好,我正在尝试循环此列表并访问嵌套字典中的特定值

[{'customer':{'name':'Karl'},{'customer':{'name':'Smith'}}]

使用此列表理解

[d for d in Account.accountList if d['customer']['name'] == 'smith']
但我得到了这个类型错误:字符串索引必须是整数,我知道这与python认为我的列表是字符串有关,但它确实是一个列表

>>> type(Account.accountList)
 <class 'list'>
你很接近

问题就在这里

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.appendself

似乎您正在将一个对象附加到AccountList,而不是预期的字典,因为self是一个对象。尝试:


Account.accountList.append{'customer':{'name':name}

是的,有。。。d是帐户的一个实例。。。不是口述。。。和uuu getitem_uuuuu返回一个字符串。。。所以,是的,这不适用于访问他的客户属性。。。也不是它的名字属性。。。因为客户根本没有实现_ugetItem _;,所以我可以告诉您。。。OP最多可以作为d[customer]访问它。如果他们修复了帐户,请命名。\uuu getitem\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuulookup@JoranBeasley为什么d是Account的实例?OP正在通过Account.accountList中存储的词典列表进行循环。感谢您的回答,它们是我的帐户的一个问题。\uuu getitem\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。我也向customer添加了一个_getitem,我可以像你说的那样使用索引来访问customer实例。太好了。。。如果这个答案有助于解决您的问题,请随意投票并接受它。。。如果您仍然需要帮助,请进一步解释MMM可能会在Account.accountList中为d打印nextd,如果d['customer']['name']=='smith',这假设您已纠正了问题,这些不是字典…它们不是字典,它们是您在OP中看到的列表,来自其帐户和客户类的报告。。。详细信息不是一份口述清单。。。。我向你保证。。。我的答案是correct@JoranBeasley是的,谢谢。不过我的措辞有点不同。在这种情况下,有一个+1为他提供了一种使其工作的方法:PThanks-man,这也是一个很好的解决方案,如果我想添加多个类实例,我会继续添加到append方法中,比如Account.accountList.append{customer':{name':name},{cash':{balance':balance}@cyclopse87您可以这样做,但效率很低。最好将对象实例附加到列表中,并使用对象而不是字典。这样,如果添加新属性,您就不会忘记更新字典。我的回答纯粹是为了说明列表理解不起作用的原因:
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']