You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在字典列表中为缺失的contents键添加含NaN的键值对

补全字典列表中缺失的键值对

针对你给出的字典列表,我们可以通过遍历+条件判断的方式,补全缺失的contents键以及其内部的type、submitted、indexed键,用'NaN'填充缺失值。以下是具体实现:

代码实现

# 原始字典列表(注意不要用list作为变量名,避免覆盖内置类型)
original_list = [{'sitemap': [{'path': 'http://test.com',
                      'errors': '0',
                      'contents': [{'type': 'web',
                                    'submitted': '34801',
                                    'indexed': '4656'}]}]},
        {'sitemap': [{'path': 'https://example.com',
                      'errors': '0',
                      'contents': [{'type': 'web', 'submitted': '2329'}]}]},
        {'sitemap': [{'path': 'https://fakeurl.com', 'errors': '0'}]}]

# 定义需要补全的内容字段
required_content_keys = ['type', 'submitted', 'indexed']
default_value = 'NaN'

# 遍历处理每个条目
for item in original_list:
    # 获取sitemap下的站点列表
    sitemap_entries = item['sitemap']
    for entry in sitemap_entries:
        # 检查是否存在contents键
        if 'contents' not in entry:
            # 缺失则添加默认内容
            entry['contents'] = [{key: default_value for key in required_content_keys}]
        else:
            # 存在则补全contents内部的缺失键
            for content in entry['contents']:
                for key in required_content_keys:
                    if key not in content:
                        content[key] = default_value

# 输出处理后的结果
print(original_list)

代码说明

  1. 层级遍历:从最外层列表开始,依次进入sitemap子列表、每个站点字典,逐层检查键的存在性。
  2. 缺失键处理逻辑:
    • 若站点字典无contents键,直接生成包含所有必填字段、值为'NaN'的字典列表赋值给contents。
    • 若contents已存在但内部字典缺失字段,遍历预设的必填字段列表,给缺失字段补'NaN'值。
  3. 扩展性:通过required_content_keys统一管理需要补全的字段,后续调整字段只需修改该列表即可。

执行上述代码后,即可得到你期望的输出格式。

内容的提问来源于stack exchange,提问作者Anchobi_codes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 11:12:42