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

如何在Python中合并列表内字典并去除空值

合并多字典并去除空值的Python实现

问题

给定这个Python列表:

my_list = [
    {"Fruit": "Apple", "Weight": "", "Variety": "Green Apple", "Amount": ""},
    {"Fruit": "Apple", "Weight": "1Kg", "Variety": "", "Amount": ""},
    {"Fruit": "Apple", "Weight": "1Kg", "Variety": "", "Amount": "2$"}
]

注:原代码里的字典键未加引号,属于语法错误,先修正为合法格式。

需要处理后得到仅含单个合并字典的列表:

my_list = [{"Fruit": "Apple", "Weight": "1Kg", "Variety": "Green Apple", "Amount": "2$"}]

核心需求是合并所有字典的键值对,只保留非空值,最终生成单字典列表。

解决方案

方法1:基础循环遍历

逻辑直白,容易理解:

my_list = [
    {"Fruit": "Apple", "Weight": "", "Variety": "Green Apple", "Amount": ""},
    {"Fruit": "Apple", "Weight": "1Kg", "Variety": "", "Amount": ""},
    {"Fruit": "Apple", "Weight": "1Kg", "Variety": "", "Amount": "2$"}
]

merged = {}
for d in my_list:
    for key, val in d.items():
        # 只在值非空且键未被赋值时更新,避免覆盖已有的非空值
        if val and key not in merged:
            merged[key] = val
        # 如果需要允许后续非空值覆盖之前的,直接用下面两行替代上面的判断:
        # if val:
        #     merged[key] = val

result = [merged]
print(result)

运行后输出:

[{'Fruit': 'Apple', 'Weight': '1Kg', 'Variety': 'Green Apple', 'Amount': '2$'}]

方法2:用itertools.chain简化代码

想写得更简洁的话,可以借助itertools模块的chain工具:

from itertools import chain

my_list = [
    {"Fruit": "Apple", "Weight": "", "Variety": "Green Apple", "Amount": ""},
    {"Fruit": "Apple", "Weight": "1Kg", "Variety": "", "Amount": ""},
    {"Fruit": "Apple", "Weight": "1Kg", "Variety": "", "Amount": "2$"}
]

# 把所有字典的键值对串联起来,筛选非空值,后面的非空值会自动覆盖前面的
merged = {k: v for k, v in chain.from_iterable(d.items() for d in my_list) if v}
result = [merged]
print(result)

这个方法利用字典推导式的特性——重复的键会保留最后一次出现的有效值,刚好匹配需求。

注意点

  • 原问题中的字典键缺少引号,这在Python中会报错,所以代码里先做了修正,确保语法合法。
  • 两种方法的区别在于是否允许后续非空值覆盖之前的,根据实际需求选择即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:50:25