小编lej*_*ang的帖子

在Python中填充空字典

我在用 Python 填充空字典时遇到问题

我将字典声明如下:

my_dict = {}
Run Code Online (Sandbox Code Playgroud)

我想一次用不同的键和不同的值填充它。我想最后有这样的东西:

{"1":(1,2,3,4),"2":(4,5,6,7),"3":(8,9,10,11),"4":(12,13,14,15)}
Run Code Online (Sandbox Code Playgroud)

因此我尝试这样做:

for i in range(4):
    for j in range(4):
         my_dict[str(i)].append(j)
Run Code Online (Sandbox Code Playgroud)

但我在第一个循环时出现以下错误:

KeyError Traceback(最近一次调用最后一次) in () 2 for i in range(4): 3 for j in range(4): ----> 4 my_dict[str(i)].append(j)
KeyError: ' 0'

我的代码中有一个更复杂的 for 循环,但我尝试尽可能更通用,以帮助其他可能遇到类似问题的人。最后我想为每个键设置不同大小的值。

如果您知道为什么它不起作用以及如何修复它,请随时回答。

编辑

抱歉造成混乱,我想要类似以下的内容:

{'1': [1, 2, 3, 4],
             '2': [5, 6, 7, 8],
             '3': [9, 10, 11, 12],
             '4': [13, 14, 15, 16]})
Run Code Online (Sandbox Code Playgroud)

python dictionary list python-3.x defaultdict

3
推荐指数
1
解决办法
2万
查看次数

标签 统计

defaultdict ×1

dictionary ×1

list ×1

python ×1

python-3.x ×1