2014-08-27 32 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}