将字典作为参数传递给函数
Pass dictionaries in function as arguments
我正在尝试创建一个函数,该函数采用未知数量的参数(字典)将它们合并为一个。这是我的草图:
weight = {"sara": 60, "nick": 79, "sem": 78, "ida": 56, "kasia": 58, "slava": 95}
height = { "a" : 1, "b": 2, "c":3 }
width = {"u": "long", "q": 55, "qw": "erre", 30: "34"}
a = {10:20, 20:"a"}
def merge(**dict):
new_dict = {}
for x in dict:
for a, b in x.items():
new_dict[a] = b
return new_dict
print(merge(weight, height, width, a))
我得到错误:
TypeError: merge() takes 0 positional arguments but 4 were given
为什么?
如果您想将 dict
中的 list
作为单个参数传递,您必须这样做:
def foo(*dicts)
无论如何你不应该将它命名为 *dict
,因为你正在下标 dict
class.
在 Python
中,您可以使用 *
运算符将所有参数作为 list
传递...
def foo(*args)
...并作为 dict
与 **
运算符
def bar(**kwargs)
例如:
>>> foo(1, 2, 3, 4) # args is accessible as a list [1, 2, 3, 4]
>>> bar(arg1='hello', arg2='world') # kwargs is accessible as a dict {'arg1'='hello', 'arg2'='world'}
在你的情况下,你可以这样编辑你的函数原型:
def merge(*dicts):
将 def merge(**dict):
更改为 def merge(*dict):
,它正在运行。避免将其命名为 dict
,因为它是 python.
中的关键字
首先注意: dict
是参数的错误名称,因为它已经是类型的名称。
当您在函数的参数列表中使用 **
时,它会吸收您未明确列出的任何关键字参数。类似地,具有单个 *
的参数会吸收所有未明确命名的额外位置参数。
考虑:
>>> def foo(bar, **baz): return (bar, baz)
...
>>> foo(42, wooble=42)
(42, {'wooble': 42})
>>> foo(bar=42, wooble=42)
(42, {'wooble': 42})
>>> foo(bar=42, wooble=42, hello="world")
(42, {'wooble': 42, 'hello': 'world'})
>>>
如果您希望将任意数量的词典作为参数,您可以使用:
def merge(*dicts):
...
因为 dicts
现在可以吸收传入的任意数量的词典。
我正在尝试创建一个函数,该函数采用未知数量的参数(字典)将它们合并为一个。这是我的草图:
weight = {"sara": 60, "nick": 79, "sem": 78, "ida": 56, "kasia": 58, "slava": 95}
height = { "a" : 1, "b": 2, "c":3 }
width = {"u": "long", "q": 55, "qw": "erre", 30: "34"}
a = {10:20, 20:"a"}
def merge(**dict):
new_dict = {}
for x in dict:
for a, b in x.items():
new_dict[a] = b
return new_dict
print(merge(weight, height, width, a))
我得到错误:
TypeError: merge() takes 0 positional arguments but 4 were given
为什么?
如果您想将 dict
中的 list
作为单个参数传递,您必须这样做:
def foo(*dicts)
无论如何你不应该将它命名为 *dict
,因为你正在下标 dict
class.
在 Python
中,您可以使用 *
运算符将所有参数作为 list
传递...
def foo(*args)
...并作为 dict
与 **
运算符
def bar(**kwargs)
例如:
>>> foo(1, 2, 3, 4) # args is accessible as a list [1, 2, 3, 4]
>>> bar(arg1='hello', arg2='world') # kwargs is accessible as a dict {'arg1'='hello', 'arg2'='world'}
在你的情况下,你可以这样编辑你的函数原型:
def merge(*dicts):
将 def merge(**dict):
更改为 def merge(*dict):
,它正在运行。避免将其命名为 dict
,因为它是 python.
首先注意: dict
是参数的错误名称,因为它已经是类型的名称。
当您在函数的参数列表中使用 **
时,它会吸收您未明确列出的任何关键字参数。类似地,具有单个 *
的参数会吸收所有未明确命名的额外位置参数。
考虑:
>>> def foo(bar, **baz): return (bar, baz)
...
>>> foo(42, wooble=42)
(42, {'wooble': 42})
>>> foo(bar=42, wooble=42)
(42, {'wooble': 42})
>>> foo(bar=42, wooble=42, hello="world")
(42, {'wooble': 42, 'hello': 'world'})
>>>
如果您希望将任意数量的词典作为参数,您可以使用:
def merge(*dicts):
...
因为 dicts
现在可以吸收传入的任意数量的词典。