cyclopse87
cyclopse87

Reputation: 629

Finding a dictionary item that is within 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):
     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

Upvotes: 2

Views: 59

Answers (3)

ILostMySpoon
ILostMySpoon

Reputation: 2409

You are working with nested dictionaries so in order to compare the name key, you have to step one more level down.

If you want just the values for a particular customer, you can use dict.values with your list comprehension like so:

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

In this case, you would get a result like this:

[{'name': 'Foo'}]

Upvotes: 2

Cody Bouche
Cody Bouche

Reputation: 955

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

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117866

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

Upvotes: 3

Related Questions