python - 如何在 Python 中将定义的字典传递给 **kwargs?

标签 python function dictionary keyword-argument

这是我第一次在这里发帖。希望我能得到好的建议:)
我学会了如何同时通过 **kwargs*args变成一个函数,它运行得很好,如下所示:

def market_prices(name, **kwargs):
     print("Hello! Welcome to "+name+" Market!")
     for fruit, price in kwargs.items():
         price_list = " {} is NTD {} per piece.".format(fruit,price)
         print (price_list) 
market_prices('Wellcome',banana=8, apple=10)
但是在实际情况下,我宁愿预先定义一个包含大量键和值的字典,这样在调用我的函数时就不必输入每个参数。我在网上搜索过,但找不到一个很好的例子或解释:/
你能给我一些建议吗?这是我尝试使用的代码:
fruits:{"apple":10,
       "banana":8,
       "pineapple":50,
       "mango":45
       }

def market_prices(name, **fruits):
    print("Hello! Welcome to "+name+" Market!")
    for fruit, price in fruits.items():
        price_list = " {} is NTD {} per piece.".format(fruit,price)
        print (price_list)

market_prices('Wellcome ', fruits)
NameError:未定义名称“水果”
非常感谢!:)

最佳答案

有4种可能的情况:

您使用 调用该函数命名参数 你想要 命名变量 在函数中:
(注意默认值)

def buy(orange=2, apple=3):
    print('orange: ', orange)
    print('apple: ', apple)

buy(apple=4)
# orange:  2
# apple:  4

您使用 调用该函数命名参数 但你想要 一本字典在函数中:
然后使用 **dictionaryname在函数定义中收集传递的参数
def buy(**shoppinglist):
    for name, qty in shoppinglist.items():
        print('{}: {}'.format(name, qty) )

buy(apple=4, banana=5)
# banana: 5
# apple: 4

你调用函数传递 一本字典但你想要 命名变量 在函数中:
使用 **dictionaryname调用函数解压字典时
def buy(icecream=1, apple=3, egg=1):
    print('icecream:', icecream)
    print('apple:', apple)
    print('egg:', egg)

shoppinglist = {'icecream':5, 'apple':1}
buy(**shoppinglist)
# icecream: 5
# apple: 1
# egg: 1

你调用函数传递 一本字典你想要 一本字典在函数中:
只是通过字典
def buy(shoppinglist):
    for name, qty in shoppinglist.items():
        print('{}: {}'.format(name, qty) )

shoppinglist = {'egg':45, 'apple':1}
buy(shoppinglist)
# egg: 45
# apple: 1

关于python - 如何在 Python 中将定义的字典传递给 **kwargs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51751929/

相关文章:

python - 如何获取python矩阵中特定项目的索引

python - 从 pandas.DataFrame 中删除所有重复项的更好策略?

Javascript - 定义属性与原型(prototype)

c++ - 通过迭代器调用函数?

python - Python如何模仿Perl多级哈希链提取和串联的行为

python - 如何修复签名中 Tensorflow 1.14.0rc 中的 'strided slice assignment are not compatible with expected types'?

python - Gmail SMTP 身份验证总是失败

PHP 邮件 HTML 格式不起作用

python - 在 Python 中使用 map on 方法

c# - 在 Google Tile Server 中平铺(x、y 和 z 参数)