[英]Return a specific dict from a list of dicts
If I had the following code 如果我有以下代码
attributes = []
attributes.append({'attribute': 'noir', 'group': 'coloris', 'id': '8'})
attributes.append({'attribute': 's', 'group': 'taille_textile', 'id': '29'})
attributes.append({'attribute': 'm', 'group': 'taille_textile', 'id': '24'})
attributes.append({'attribute': 'l', 'group': 'taille_textile', 'id': '25'})
attributes.append({'attribute': 'xl', 'group': 'taille_textile', 'id': '26'})
and I wanted to return an object of the list which contained a certain id, what would be the best way to do that? 我想返回列表中包含某个id的对象,最好的方法是什么?
I know that one solution would be to use the for
loop like this 我知道一个解决方案就是像这样使用for
循环
def getItemById(id):
for i in attributes:
for k,v in i.items():
if (k == 'id' and v == id):
return i
I'm sure there must be a much more elegant or efficient way to do it other than this? 我敢肯定除此之外必须有更优雅或更有效的方法吗?
Is there an opportunity to use lambdas here? 这里有机会使用lambdas吗? would that give a performance benefit? 这会带来性能上的好处吗?
你可以使用一个发电机:
next(attr for attr in attributes if attr['id'] == id_to_find)
For example, you want to return object with 'id'='29'
例如,您想要返回'id'='29'
This works 这有效
[x for x in attributes if x['id']=='29'][0]
{'attribute': 's', 'group': 'taille_textile', 'id': '29'}
Another approach is to convert List to a pandas DataFrame. 另一种方法是将List转换为pandas DataFrame。
import pandas as pd
df = pd.DataFrame(attributes)
#get all columns where id=8
print df[df['id']=='8']
#get specific column where id=29
print df['attribute'][df['id']=='29']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.