我有一个字典的python列表。 如何根据密钥获取特定字典?
示例输入:
dict_input = [{"name":"kishore", "age":23}, {"name":"xyz", "age":21}]
现在我如何获得具有键名称和值kishore不通过整个列表的字典
我期待O(1)查找。
答案 0 :(得分: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", "?")
'?'