简体   繁体   English

将 function 中的字典传递为 arguments

[英]Pass dictionaries in function as arguments

Im trying to create a function that take unknown number of arguments (dictionaries) to merge them in one.我试图创建一个 function ,它需要未知数量的 arguments (字典)将它们合并为一个。 Here is my sketch:这是我的草图:

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))

And I got error:我得到了错误:

TypeError: merge() takes 0 positional arguments but 4 were given

Why?为什么?

Change def merge(**dict): to def merge(*dict): and it is working. def merge(**dict):更改为def merge(*dict):并且它正在工作。 Avoid naming it dict since it is a keyword in python.避免将其命名为dict ,因为它是 python 中的关键字。

First note: dict is a bad name for an argument as it is already the name of a type.首先注意: dict是一个参数的坏名称,因为它已经是一个类型的名称。

When you use ** in the argument list for a function it is slurping up any keyword arguments you haven't explicitly listed.当您在 function 的参数列表中使用**时,它会占用您未明确列出的任何关键字 arguments。 Similarly, a parameter with a single * is slurping up any extra positional arguments not explicitly named.同样,带有单个*的参数会占用任何未明确命名的额外位置 arguments。

Consider:考虑:

>>> 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'})
>>>

If you wish to take any number of dictionaries as arguments, you'd use:如果您希望将任意数量的字典用作 arguments,您可以使用:

def merge(*dicts):
    ...

As dicts will now slurp up any number of dictionaries passed in.因为dicts现在会吞掉传入的任意数量的字典。

If you want to pass a list of dict s as a single argument you have to do this:如果您想将dict list作为单个参数传递,您必须这样做:

def foo(*dicts)

Anyway you SHOULDN'T name it *dict , since you are subscripting the dict class.无论如何,您不应该将其命名为*dict ,因为您正在为dict class 下标。


In Python you can pass all the arguments as a list with the * operator...Python ,您可以使用*运算符将所有 arguments 作为list传递...

def foo(*args)

...and as a dict with the ** operator ...并作为带有**运算符的dict

def bar(**kwargs)

For example:例如:

>>> 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'}

In your case you can edit the prototype of you function this way:在您的情况下,您可以通过以下方式编辑 function 的原型:

def merge(*dicts):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM