Python 如何从当前函数中的另一个函数访问词典

Python 如何从当前函数中的另一个函数访问词典,python,function,dictionary,parameters,arguments,Python,Function,Dictionary,Parameters,Arguments,我想查一下功能一中的词典。我尝试返回字典变量,并使用字典名称作为参数和参数。但是,我收到一条错误消息,说我试图在函数\ 2中访问的字典没有定义 以下是我的简化代码: def function_one(): first_dictionary = {"text1": "text2","text3": "text4"} second_dictionary = {"example1": "example2","example3": "example4"} for i in fi

我想查一下功能一中的词典。我尝试返回字典变量,并使用字典名称作为参数和参数。但是,我收到一条错误消息,说我试图在函数\ 2中访问的字典没有定义

以下是我的简化代码:

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)

基本上,我是在询问为input1选择的元素是否在上一个函数的字典中。我希望程序更改总成本值等。

您需要首先从函数返回值。 您可以执行以下操作:

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

否则,您可以使用大多数情况下不推荐使用的全局变量。

当您调用
函数\u one()
时,您没有使用它返回的字典。 您可以使用此解决您的问题:

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

您没有获得返回值:

first\u dictionary,second\u dictionary=function\u one()

使用返回值、全局变量或包含这些字典的类。目前,您没有对
function\u one()
返回的值进行任何处理。非常感谢!我花了很长时间想弄明白。