首页 > 解决方案 > 如果键不存在,Python将键添加到字典列表

问题描述

我想将键“名称”添加到字典列表中的字典“名称”不存在。

例如,

[dict(item, **{'Name': 'apple'}) for item in d_list] 

即使键已经存在,也会更新键“名称”的值,并且

[dict(item, **{'Name': 'apple'}) for item in d_list if 'Name' not in item]

返回空列表

标签: pythonlistdictionarykey

解决方案


您需要处理这两种不同的情况。如果列表为空,如果不是。

不可能在单个列表理解语句中处理这两个用例,因为当列表为时,它将始终返回零值(空列表)。这就像在做for i in my_list。如果列表为空,则不会执行 for 块中的代码。

我会用一个循环来解决它。我觉得它更具可读性。

>>> default = {"Name": "apple"} 
>>> miss_map = {"Data": "text"}
>>> exist_map = {"Name": "pie"}
>>>
>>> d = [miss_map, exist_map]
>>>
>>> list_dict = [miss_map, exist_map]
>>> for d in list_dict:
...     if "Name" not in d.keys():
...             d.update(default)
...
>>> list_dict
[{'Data': 'text', 'Name': 'apple'}, {'Name': 'pie'}]
>>>

然后,您可以将其移至它自己的函数并将其传递给字典列表。


推荐阅读