user4444
user4444

Reputation: 45

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

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.

Upvotes: 0

Views: 1127

Answers (3)

Balaji Ambresh
Balaji Ambresh

Reputation: 5012

You didn't get the return value:

first_dictionary,second_dictionary = function_one()

Upvotes: 3

Usama
Usama

Reputation: 529

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)

Upvotes: 3

Leonid Ivanov
Leonid Ivanov

Reputation: 381

You need to return values from the function_one() first. You can do the following:

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

Otherwise, you can use global variables that is not recommended in most cases.

Upvotes: 3

Related Questions