How to add items to a dictionary between two methods?

Question:

I’m writing a method that takes in a list and returns a dictionary. This method is to be saved in a separate Python file and imported into Main.py

The method that takes in a list calls another method that’s meant to update the global dictionary.

global myDict

def addKeyValuePair(listItem):
    try: 
        key = listItem.split(': ')[0].replace('\','')
        value = listItem.split(': ')[1].replace('\r\n','').replace('\','')
        myDict.update({key:value})
    except:
        pass 

def makeDict(dataList):
     myDict =  {}
     for listItem in dataList:
        addKeyValuePair(listItem)

     return(myDict)

From the main method I’m importing the makeDict module and passing it the dataList, but it returns an empty dictionary.

from Toolkit import makeDict

finalDict = makeDict(dataList)

Any idea how this can be done?

Asked By: ortunoa

||

Answers:

There are a few issues with the code you posted.

First, you are trying to access a global variable called myDict from inside the makeDict function. However, you also define a local variable with the same name inside the function, which shadows the global variable. As a result, any modifications made to the local myDict inside the function do not affect the global myDict.

One way to fix this would be to remove the local myDict variable and just use the global myDict variable inside the makeDict function. However, using global variables in this way can make your code difficult to understand and maintain. A better approach would be to pass the dictionary as an argument to the makeDict function, and return the updated dictionary from the function.

Here is how you could modify the code to fix these issues:

myDict = {}

def addKeyValuePair(myDict, listItem):
    try: 
        key = listItem.split(': ')[0].replace('\','')
        value = listItem.split(': ')[1].replace('\r\n','').replace('\','')
        myDict.update({key:value})
    except:
        pass 

def makeDict(dataList):
    myDict =  {}
    for listItem in dataList:
        addKeyValuePair(myDict, listItem)

    return myDict

To use this updated makeDict function, you would call it like this:

from Toolkit import makeDict

finalDict = makeDict(dataList)

I hope this helps!

Answered By: Guido Carugati