Python:将字典作为参数传递给函数

2021年3月17日14:47:57 发表评论 3,646 次浏览

Python中的字典是无序且可变的数据集合。与列表使用的数字索引不同, 字典使用键作为特定值的索引。它可以用于存储不相关的数据类型, 但可以存储与实际实体相关的数据。使用密钥本身来使用特定值。

请参阅以下文章, 以获取有关Python字典的想法。 Python字典

通过字典作为参数

在Python中, 一切都是对象, 因此可以像传递其他变量一样将字典作为参数传递函数

例子:

# Python program to demonstrate
# passing dictionary as argument
  
  
# A function that takes dictionary
# as an argument
def func(d):
      
     for key in d:
         print ( "key:" , key, "Value:" , d[key])
          
# Driver's code
D = { 'a' : 1 , 'b' : 2 , 'c' : 3 }
func(D)

输出如下:

key: b Value: 2
key: a Value: 1
key: c Value: 3

通过字典作为kwargs

"夸格斯"代表关键字参数。它用于将高级数据对象(如字典)传递给函数, 因为在此类函数中, 人们不了解参数的数量, 因此, 通过在传递的类型上添加" **"可以正确处理传递的数据。

范例1:

# Python program to demonstrate
# passing dictionary as kwargs
  
  
def display( * * name):
      
     print (name[ "fname" ] + " " + name[ "mname" ] + " " + name[ "lname" ])
  
def main():
      
     # passing dictionary key-value 
     # pair as arguments
     display(fname = "John" , mname = "F." , lname = "Kennedy" )
# Driver's code
main()

输出如下:

John F. Kennedy

范例2:

# Python program to demonstrate
# passing dictionary as kwargs
  
  
def display(x = 0 , y = 0 , * * name):
      
     print (name[ "fname" ] + " " + name[ "mname" ] + " " + name[ "lname" ])
     print ( "x =" , x)
     print ( "y =" , y)
  
def main():
     # passing dictionary key-value 
     # pair with other arguments
     display( 2 , fname = "John" , mname = "F." , lname = "Kennedy" )
      
# Driver's code
main()

输出如下:

John F. Kennedy
x = 2
y = 0

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

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


木子山

发表评论

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