[英]Find a dictionary based on a key in list of dictionaries in python
我有字典的python列表。 如何根據密鑰獲取特定的詞典?
輸入示例:
dict_input = [{"name":"kishore", "age":23}, {"name":"xyz", "age":21}]
現在如何獲取具有鍵名和值kishore的字典而不遍歷整個列表
我期望查找O(1)。
不迭代列表就不可能獲得項目。
使用生成器表達式和next
:
>>> dict_input = [{"name":"kishore", "age":23},{"name":"xyz", "age":21}]
>>> next((d for d in dict_input if d['name'] == 'kishore'), None)
{'age': 23, 'name': 'kishore'}
>>> next((d for d in dict_input if d['name'] == 'no-such-name'), None)
>>> next((d for d in dict_input if d['name'] == 'no-such-name'), None) == None
True
如果應該多次進行查找並且您不希望遍歷整個列表項,則可以構建字典。
>>> dict_input = {
... "kishore": {"name":"kishore", "age":23},
... "xyz": {"name":"xyz", "age":21}
... }
>>> dict_input["kishore"]
{'age': 23, 'name': 'kishore'}
>>> dict_input["no-such-name"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'no-such-name'
>>> dict_input.get("no-such-name", "?")
'?'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.