[英]Filling empty dictionary in Python
I have trouble filling an empty dictionary in Python 我在用Python填充空字典时遇到麻烦
I declare the dictionary as follow : 我将字典声明如下:
my_dict = {}
I want to fill it with different key and differents values one at a time. 我想一次用不同的键和不同的值填充它。 I would like to have at the end something like :
我希望最后有类似的东西:
{"1":(1,2,3,4),"2":(4,5,6,7),"3":(8,9,10,11),"4":(12,13,14,15)}
Therefore I tried to do it as follow : 因此,我尝试按照以下步骤进行操作:
for i in range(4):
for j in range(4):
my_dict[str(i)].append(j)
But I have the following error at the first loop : 但是在第一个循环中我遇到以下错误:
KeyError Traceback (most recent call last) in () 2 for i in range(4): 3 for j in range(4): ----> 4 my_dict[str(i)].append(j)
()中的KeyError Traceback(最近一次通话最后一次)(2)范围(4)中的i:3范围(4)中的j:----> 4 my_dict [str(i)]。append(j)
KeyError: '0'KeyError:“ 0”
I have a much more complicated for loop in my code but I tried to be the more general as possible to help other who might have a similar problem. 我的代码中的for循环要复杂得多,但我尝试尽可能地笼统一些,以帮助其他可能遇到类似问题的人。 At the end I would like to have different size's value for each key.
最后,我希望每个键具有不同的大小值。
If you have any idea why it does not work and how to fix it please feel free to answer. 如果您知道为什么它不起作用以及如何解决它,请随时回答。
EDIT 编辑
Sorry for the confusion, I wanted something like the following : 抱歉让我感到困惑,我想要以下内容:
{'1': [1, 2, 3, 4],
'2': [5, 6, 7, 8],
'3': [9, 10, 11, 12],
'4': [13, 14, 15, 16]})
There are 2 issues: 有两个问题:
KeyError
. KeyError
的原因。 These issues can be alleviated by using collections.defaultdict
with list
: 这些问题可以通过将
collections.defaultdict
与list
一起使用来缓解:
from collections import defaultdict
my_dict = defaultdict(list)
for i in range(4):
for j in range(4):
my_dict[str(i)].append(j)
print(my_dict)
defaultdict(list,
{'0': [0, 1, 2, 3],
'1': [0, 1, 2, 3],
'2': [0, 1, 2, 3],
'3': [0, 1, 2, 3]})
Closer to your desired output, you will need to redefine your range
objects: 更接近所需的输出,您将需要重新定义
range
对象:
my_dict = defaultdict(list)
for i in range(1, 5):
for j in range((i-1)*4+1, i*4+1):
my_dict[str(i)].append(j)
print(my_dict)
defaultdict(list,
{'1': [1, 2, 3, 4],
'2': [5, 6, 7, 8],
'3': [9, 10, 11, 12],
'4': [13, 14, 15, 16]})
You can create this dict
, with a list as values, using a little dict comprehension: 您可以使用一点dict理解来创建此
dict
,并使用列表作为值:
my_dict = {str(i+1): [j for j in range((i*4)+1, (i+1)*4+1)] for i in range(4)}
EDIT: OP realized he wanted a list, not a tuple. 编辑:OP意识到他想要一个列表,而不是一个元组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.