简体   繁体   English

将字典传递给带有解包参数的函数

[英]Passing a dictionary to a function with unpacking argument

This below snippet of code gives me this error TypeError: pop() argument after ** must be a mapping, not tuple .下面的代码片段给了我这个错误TypeError: pop() argument after ** must be a mapping, not tuple

class a():
    data={'a':'aaa','b':'bbb','c':'ccc'}
    def pop(self, key, **args):
        return self.data.pop(key, **args)

b=a()
print(b.pop('a',{'b':'bbb'}))

But when I replace double ** with single * , this works fine.但是当我用单*替换双**时,这很好用。 As per my understanding , if we are passing a dictionary , we should have double ** .根据我的理解,如果我们传递字典,我们应该有双** In this case the second argument what's being passed is dictionary {'b':'bbb'} .在这种情况下,传递的第二个参数是字典{'b':'bbb'} Then how is it throwing error in first case but not in second case?那么它是如何在第一种情况下抛出错误而不是在第二种情况下抛出错误的呢?

class a():
    data={'a':'aaa','b':'bbb','c':'ccc'}
    def pop(self, key, *args):
        return self.data.pop(key, *args)

b=a()
print(b.pop('a',{'b':'bbb'})

If you want a dictionary to be used as keyword arguments, you have to use the ** in the call as well:如果您希望将字典用作关键字参数,则还必须在调用中使用**

print(b.pop('a',**{'b':'bbb'}))

But I don't think that's really what you wanted anyway.但我不认为这真的是你想要的。

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

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