how to access a dictionary from another function in the current function

Tags: , , , ,



I am trying to refer to the dictionary in function_one. I have tried to return the dictionary variables, and use the dictionary names as parameters and arguments. However, I am getting an error message saying that the dictionaries I am trying to access in function_two is not defined.

Here is my simplified code:

def function_one():
    first_dictionary = {"text1": "text2","text3": "text4"}
    second_dictionary = {"example1": "example2","example3": "example4"}

    for i in first_dictionary:
        print(i,first_dictionary[i])

    for i in second_dictionary:
        print(i,second_dictionary[i])

    return first_dictionary,second_dictionary

def function_two(first_dictionary,second_dictionary):
    total_cost = 0
    input1 = True
    while input1 != '0':
        input1 = input("Input1")
        input2 = int(input("Input2".format(input1)))
        if input1 in first_dictionary:
            total_cost += input2 * 5
        elif input1 in second_dictionary:
            total_cost += input2 * 4

#main Routine

function_one()
function_two(first_dictionary,second_dictionary)

Basically, I am asking if the element chosen for input1 is in the dictionary in the previous function I want the program to change the total_cost value etc.

Answer

When you are calling the function_one(), you are not using the dictionaries returned by it. You can use this to solve your problem:

first_dictionary, second_dictionary = function_one()
function_two(first_dictionary,second_dictionary)


Source: stackoverflow