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

Python如何为字典添加缺失的连续数字键并赋值为空字符串

Python字典补全缺失键的实现方法

实现思路

先获取原字典的最大键值,遍历1到该最大键的所有整数,将不存在于原字典的数字设为新键,对应值统一赋值为空字符串即可。

代码示例

原字典

x = {6: {"Apple", "Banana", "Tomato"}, 9: {"Cake"}, 11: {"Pineapple", "Apple"}}

实现代码

# 取字典的最大键值
max_key = max(x.keys())
# 补全缺失键
for num in range(1, max_key + 1):
    if num not in x:
        x[num] = ""
# 若需要键按升序排列,Python3.7+默认保留插入顺序,低于该版本可加以下代码
x = dict(sorted(x.items()))

运行结果

执行后打印x即可得到目标结构:

{1: '', 2: '', 3: '', 4: '', 5: '', 6: {'Apple', 'Banana', 'Tomato'}, 7: '', 8: '', 9: {'Cake'}, 10: '', 11: {'Apple', 'Pineapple'}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:15:04