【问题标题】:how to access a dictionary from another function in the current function如何从当前函数中的另一个函数访问字典
【发布时间】:2020-10-10 10:34:00
【问题描述】:

我正在尝试引用 function_one 中的字典。我试图返回字典变量,并将字典名称用作参数和参数。但是,我收到一条错误消息,指出我试图在 function_two 中访问的字典未定义。

这是我的简化代码:

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 选择的元素是否在上一个函数的字典中,我希望程序更改 total_cost 值等。

【问题讨论】:

  • 要么使用返回值、全局变量或包含这些字典的类。就目前而言,您没有对来自 function_one() 的返回值做任何事情。

标签: python function dictionary parameters arguments


【解决方案1】:

当您调用function_one() 时,您并没有使用它返回的字典。 你可以用它来解决你的问题:

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

【讨论】:

    【解决方案2】:

    您需要先从 function_one() 返回值。 您可以执行以下操作:

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

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

    【讨论】:

      【解决方案3】:

      你没有得到返回值:

      first_dictionary,second_dictionary = function_one()
      

      【讨论】:

      • 非常感谢!我花了很长时间试图弄清楚这一点。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      相关资源
      最近更新 更多