Search code examples
pythonpython-3.xlistdictionarydefaultdict

Filling empty dictionary in Python


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]})

Solution

  • There are 2 issues:

    1. You cannot append to a tuple. Tuples are immutable.
    2. 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]})