[英]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. 嗨,我正在尝试找到访问列表中字典值的最佳方法,我有一个Account类,正在尝试将Customer嵌入到使用组合中。 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 当我运行
accountList
我得到
[{'customer': {'name': 'Foo'}}, {'customer': {'name': 'bar'}}]
I would like to find a way to access each customer from this accountList
我想找到一种从此
accountList
访问每个客户的方法
I'v tried list comprehension like so [d for d in Account.accountList if d["name"] == "smith"]
我已经尝试过列表理解,例如
[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
您的列表理解很接近,但是您需要再下一层检查,因为每个列表项d
是一个dict
,而与键'customer'
相对应的值本身就是另一个dict
。
[d for d in Account.accountList if d['customer']['name'] == 'smith']
You are working with nested dictionaries so in order to compare the name
key, you have to step one more level down. 您正在使用嵌套词典,因此为了比较
name
键,您必须再向下一级。
If you want just the values for a particular customer, you can use dict.values
with your list comprehension like so: 如果只需要特定客户的值,则可以将
dict.values
用于列表dict.values
,如下所示:
[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'}]
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.