Search code examples
pythondictionaryruntime-error

Creating a dynamic dictionary and assigning it new keys in a loop (Python)


Hello there, hope you are all doing well.

I am doing an assignment right now for Image Processing and I need to create a greyscale image histogram example. However, histogram values will be set according to user input. Let me explain with an example.

If the user inputs 128 as the histogram value, that means histogram is going to have 128 levels, these are:

[0, 1], [2, 3], [3, 4], ..... , [254, 255] (Which makes 128 sets)

If the user inputs 64 as the histogram value, that means histogram is going to have 64 levels, these are:

[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], ..... , [252, 253, 254, 255] (which makes 64 sets)

Now I am trying to create a code that is able to create the sets according to the histogram value input. It looks this at the moment:

import cv2
import numpy as np
def getHistogram(bin):  

    # Initializing the dictionary and the first key of it:
    rangeDict = {
    "set0": []
    }

    # Acquiring the increment value:
    increment = int(256 / bin)

    # Initializing the start and stop values:
    start = 0
    stop = start + increment
    
    while True:

        # Adding the numbers to the key one after another in a single list, according to the user input:
        for i in range(start, stop):
            rangeDict["set" + str(i)].append(start + i)

        # When 255 is reached in the dictionary, loop will terminate:
        if rangeDict["set" + str(i)][-1] == 255:
            break

        else:
            # Assigning the greatest value in the most recently added key to the start:
            start = rangeDict["set" + str(i)][-1] 
            # Assigning start, plus the increment
            stop = start + increment
            # Initializing the next key:
            rangeDict["set" + str(i + 1)] = []
    # Printing the dictionary for checking:
    print(rangeDict)

# main:
getHistogram(128)

However when I run the code, I get "KeyError: set1". However I was not expecting to have this kind of an error since I initialize the new key in the loop. Am I missing something? If I am able to create the sets of histogram, the rest is going to be very easy. Thank you for your help in advance!


Solution

  • The problem is rangeDict["set" + str(i)].append(start + i)

    It tries to get rangeDict["set" + str(i)] as a list, but since it doesn't exist yet it can't append so it throws an KeyError.

    Split it to

    try:
    
    
       rangeDict["set" + str(i)].append(start + i)
    
    except KeyError:
        rangeDict["set" + str(i)] = [start +i]