python-3.x - 如何在 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]}”键值。那么,如何从另一个函数中的一个函数访问字典的键值呢?
解决方案
有几种方法可以实现这一点,一种是返回整个字典并循环遍历这个新字典,但是我会这样实现它:
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
推荐阅读
- reactjs - 无法使用 Context API 检索对象 AsyncStorage 的值
- shopify - Shopify 临时站点
- laravel - 如何制作没有重定向到页面 404 laravel 的 slug
- javascript - 从 OAuth 回调重定向到弹出行为
- flutter - 我正在尝试从 VS 代码在模拟器上运行我的颤振应用程序,但我收到一条错误消息,说它找不到我的 main.dart 文件的路径
- botframework - 生成 Direct Line 令牌的问题
- mysql - 根据分布在 3 个表中的状态、ID 和时间验证获取可用用户
- c++ - C++:使用参数包显式调用函数重载
- html - 调整到小于 600 像素时,段落不响应 100% 宽度
- python - sub() 缺少 1 个必需的位置参数:“字符串”