Python如何将字典作为关键字参数传递?示例

2021年3月12日13:27:08 发表评论 689 次浏览

由于使用OOP范例, 许多时候使用Python字典工作时, 模块化都集中在编程的不同方面。因此, 在很多用例中, 我们需要将字典作为参数传递给函数。但这需要解开字典键作为参数, 并将其值作为参数值。让我们讨论一种可以执行此操作的方法。

方法:使用

**

(splat)运算符

该运算符用于解压缩字典, 而在传入函数时可以解压缩字典并完成将键映射到参数以及将其值映射到参数值的必需任务。

# Python3 code to demonstrate working of
# Passing dictionary as keyword arguments
# Using ** ( splat ) operator
  
# Helper function to demo this task
def test_func(a = 4 , b = 5 ):
     print ( "The value of a is : " + str (a))
     print ( "The value of b is : " + str (b))
  
# initializing dictionary
test_dict = { 'a' : 1 , 'b' : 2 }
  
# printing original dictionary
print ( "The original dictionary is : " + str (test_dict))
  
# Testing with default values 
print ( "The default function call yields : " )
test_func()
  
print ( "\r" )
  
# Passing dictionary as keyword arguments
# Using ** ( splat ) operator
print ( "The function values with splat operator unpacking : " )
test_func( * * test_dict)

输出:

The original dictionary is : {'a': 1, 'b': 2}
The default function call yields : 
The value of a is : 4
The value of b is : 5

The function values with splat operator unpacking : 
The value of a is : 1
The value of b is : 2

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: