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

Python如何根据指定列表将值为列表的字典重构为存在/不存在分组

问题说明

现有一个值为列表类型的字典source,结构如下:

source = {"name":["hans","james","mat"],"country":["spain"],"language":["english","french"]}

另有一个存储不存在项的列表data_not_avail,内容如下:

data_not_avail = ["hans","spain","mat"]

需要将source字典重构,拆分为包含exist(存在项)、not_exist(不存在项)两个子字典的结构,目标输出如下:

{
 "exist":{"name":["james"], "language":["english","french"]},
 "not_exist":{"name":["hans","mat"], "country":["spain"]}
}

此前尝试通过查找列表元素所属字典键的方式实现未成功,已编写的尝试代码如下:

data_result = {}
keys_list = []
for v in data_not_avail:
    keys = [key for key, value in source.items() if v in value]
    data_result.update({keys[0]:[v]})
    keys_list.extend(keys)
问题分析

原有代码的核心问题有两个:

  • 遍历不存在项给对应键赋值时,每次都会把键对应的值覆盖为单元素列表,同一个键下的多个不存在项会被覆盖,比如name键下的hans和mat最终只会保留最后遍历到的一个
  • 没有搭建exist/not_exist的两层结果结构,也没有处理每个键下剩余的存在项,无法输出要求的格式
实现方案

直接遍历源字典的每个键值对,对每个值列表内的元素逐一判断归属,分别归入存在/不存在分组即可,逻辑简单易读:

result = {"exist": {}, "not_exist": {}}

for k, items in source.items():
    exist = []
    not_exist = []
    for item in items:
        if item in data_not_avail:
            not_exist.append(item)
        else:
            exist.append(item)
    # 仅当分组非空时才写入对应键,避免生成值为空列表的无效键
    if exist:
        result["exist"][k] = exist
    if not_exist:
        result["not_exist"][k] = not_exist

运行上述代码得到的结果和目标输出完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 17:43:14