2014-08-27 54 views
-1

对象的列表元素我有对象的列表中的Python:查找具有明确的键值

accounts = [ 
    { 
     'id': 1, 
     'title': 'Example Account 1' 
    }, 
    { 
     'id': 2, 
     'title': 'Gow to get this one?' 
    }, 
    { 
     'id': 3, 
     'title': 'Example Account 3' 
    }, 
] 

我需要使用id = 2的对象。

当我只知道对象属性的值时,如何从此列表中选择适当的对象?

+1

[查找列表中的对象的属性等于某个值(满足任何条件)]的可能的重复](http://stackoverflow.com/questions/7125467/find-object-in-list-that-has-attribute -equal-to-some-value-that-meets-any-condi) – 2014-08-27 13:17:46

回答

2

鉴于你的数据结构:

>>> [item for item in accounts if item.get('id')==2] 
[{'title': 'Gow to get this one?', 'id': 2}] 

如果项目不存在:

>>> [item for item in accounts if item.get('id')==10] 
[] 

话虽这么说,如果有机会的话,你可能会重新考虑你的datastucture:

accounts = { 
    1: { 
     'title': 'Example Account 1' 
    }, 
    2: { 
     'title': 'Gow to get this one?' 
    }, 
    3: { 
     'title': 'Example Account 3' 
    } 
} 

你可能不会如果您希望处理不存在的密钥,则可以通过索引id或使用get()直接访问您的数据。

>>> accounts[2] 
{'title': 'Gow to get this one?'} 

>>> account[10] 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'account' is not defined 

>>> accounts.get(2) 
{'title': 'Gow to get this one?'} 
>>> accounts.get(10) 
# None 
+1

可能会更好地使用'if item.get('id')== 2',以防某些字典中不包含密钥 – 2014-08-27 13:18:23

0

这将有一个id == 2

limited_list = [element for element in accounts if element['id'] == 2] 
>>> limited_list 
[{'id': 2, 'title': 'Gow to get this one?'}] 
0

这似乎是一个奇怪的数据结构返回列表中的任何元素,但它可以做到:

acc = [account for account in accounts if account['id'] == 2][0] 

也许以ID号为密钥的字典更合适,因为这使得访问更容易:

account_dict = {account['id']: account for account in accounts}