查找列表中的字典项

时间:2015-09-09 18:12:48

标签: python dictionary nested-lists

您好我正在尝试找到访问列表中的字典值的最佳方法,我有一个Account类,我试图将Customer嵌入到使用组合中。嵌入客户后,我想将创建的所有实例附加到列表中。最后,我想找到一种方法从这个列表中获取每个客户的价值。

当我运行[{'customer': {'name': 'Foo'}}, {'customer': {'name': 'bar'}}]时,我得到了

accountList

我想找到一种方法从这个[d for d in Account.accountList if d["name"] == "smith"]

访问每个客户

我尝试了列表理解,如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

但它似乎不起作用,因为我得到一个空列表是输出[]

守则

{{1}}

3 个答案:

答案 0 :(得分:3)

您的列表理解已接近,但您需要再检查一个级别,因为每个列表项d都是dict,并且对应于键'customer'的值本身就是另一个dict

[d for d in Account.accountList if d['customer']['name'] == 'smith']

答案 1 :(得分:2)

您正在使用嵌套词典,因此为了比较name键,您必须再降低一级。

如果您只想要特定客户的值,则可以dict.values使用列表理解,如下所示:

[vals for vals in d.values() for d in Account.accountList if d['customer']['name'] == 'Foo']

在这种情况下,您会得到如下结果:

[{'name': 'Foo'}]

答案 2 :(得分:0)

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

Account('Jenny')
Account('John')
Account('Bradley')

print [d for d in Account.accountList if d.customer.name == 'Jenny']
相关问题