Finding a dictionary item from a list


Hi I am trying to find the best way to access a dictionary value that is within a list, , I have an Account class which I am trying to embed a Customer in using composition. Once I embed the customer I want to append all instances created into a list. Finally I would like to find a way to Get the values of the each customer from this list.

When I run the accountList I get

[{'customer': {'name': 'Foo'}}, {'customer': {'name': 'bar'}}]

I would like to find a way to access each customer from this accountList

I'v tried list comprehension like so [d for d in Account.accountList if d["name"] == "smith"]

But it doesn't seem to work as i get an empty list is an output []

The Code

class Customer:

  def __init__(self, name): = name

  def __repr__(self):
     return repr(self.__dict__)

class Account:

  accountList = []
  def __init__(self, name):
    self.customer = Customer(name)

  def __repr__(self):
    return repr(self.__dict__)

  def __getitem__(self, i):
    return i

Your list comprehension is close, but instead you would need to check one more level down, because each list item d is a dict, and the value corresponding to the key 'customer' is itself another dict.

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