python - 如果键不存在,Python将键添加到字典列表
问题描述
我想将键“名称”添加到字典列表中的字典“名称”不存在。
例如,
[dict(item, **{'Name': 'apple'}) for item in d_list]
即使键已经存在,也会更新键“名称”的值,并且
[dict(item, **{'Name': 'apple'}) for item in d_list if 'Name' not in item]
返回空列表
解决方案
您需要处理这两种不同的情况。如果列表为空,如果不是。
不可能在单个列表理解语句中处理这两个用例,因为当列表为空时,它将始终返回零值(空列表)。这就像在做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'}]
>>>
然后,您可以将其移至它自己的函数并将其传递给字典列表。
推荐阅读
- ffmpeg - 使用特定的叠加起始位置从左到右移动叠加
- php - 返回 eloquent 模型关系时获取空值
- typescript - 打字稿,无法读取存储在 sessionStorage 中的数组
- ruby - ruby 中的 (+=) 等速记运算符到底有什么作用?
- r - 在R中乘以2个非常大的数据帧
- reactjs - useMemo 与数组依赖关系?
- c - 如何从作为“数组”的 IDispatch 接口获取成员?
- javascript - 无法解析“E:\React\react-demo\src”中的“/images/img-2.jpg”
- python - 无论资源类型如何,如何获取 AWS 账户中的所有资源
- c# - Micorsoft.Data.SqlClient 不适用于 Microsoft.Aspnet.Identity 连接