繁体   English   中英

遍历嵌套字典列表

[英]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'>

我已经尝试过嵌套循环,但我一直收到此错误,任何帮助将不胜感激。

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}})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM