Filling empty dictionary in Python
Solution 1
There are 2 issues:
- You cannot append to a tuple. Tuples are immutable.
- You cannot append to a dictionary value which has not yet been defined for a specific key. This is the cause of your
KeyError
.
These issues can be alleviated by using collections.defaultdict
with 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:
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]})
Solution 2
You can create this dict
, with a list as values, using a little dict comprehension:
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.
Related videos on Youtube
lejcestlesang
Updated on June 04, 2022Comments
-
lejcestlesang almost 2 years
I have trouble filling an empty dictionary in 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: '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. 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]})
-
Sanchit almost 6 yearsFirst thing, dictionary does not have append() method. And, you have to assign the value to a corresponding key as: my_dict[key] = value.
-
dopstar almost 6 years
"1":(1,2,3,4),"2":(4,5,6,7)
should be"1":(1,2,3,4),"2":(5,6,7,8)
and so on
-
-
lejcestlesang almost 6 yearsThank you. That is exactly what I was trying to do !