首页 > 解决方案 > 如何在 Python 3 中将字典的键和值从一个函数引用和访问到另一个函数?

问题描述

我们应该如何将一个函数(即方法)中字典中的键值引用到另一个函数中?我的一段python代码如下 -

def function1 (x1, x2):
    dict1 = {'k1':x1, 'k2':x2}
    return 

def function2 ():

    # Here function1() is being called and passing 10 into x1 and 20 into x2 of function1 ()... 
    function1(10,20)
    print(f"First Value is: {dict1[k1]}"
          f"Second Value is: {dict1[k2]}")

我想要的结果如下 -

第一个值为:10

第二个值为:20

但我无法访问来自 function2() 内的 function1() 的 dict1{} 的“{dict1[k1]}”和“{dict1[k2]}”键值。那么,如何从另一个函数中的一个函数访问字典的键值呢?

标签: python-3.xfunctiondictionaryreturn

解决方案


有几种方法可以实现这一点,一种是返回整个字典并循环遍历这个新字典,但是我会这样实现它:

def function1 (x1, x2):
    dict1 = {'k1':x1, 'k2':x2}
    return dict1.values()

def function2 ():

    # Here function1() is being called and passing 10 into x1 and 20 into x2 of function1 ()...
    x, y = function1(10,20)
    print(f"First Value is: {x}"
          f"\nSecond Value is: {y}")
function2()

通过只返回值可以避免循环

输出:

First Value is: 10
Second Value is: 20

推荐阅读