解压字典并作为关键字参数传递给函数

ET-*_*-CS 5 python dictionary argument-unpacking python-3.x google-cloud-pubsub

我正在尝试在 python 中将一些 dict 解压缩到一些函数中:

我有一个packet作为参数的函数(应该是dict)

def queue(self, packet):
    self.topic.publish(self.message, self.client, **packet)
Run Code Online (Sandbox Code Playgroud)

我这样称呼它:

queue({
        'an_item': 1,
        'a_key': 'value'
    })
Run Code Online (Sandbox Code Playgroud)

发布功能位于第 3 方 api(Google Pub/Sub API)中,并且来自我查看的源代码:

def publish(self, message, client=None, **attrs):
    ...
    message_data = {'data': message, 'attributes': attrs}
    message_ids = api.topic_publish(self.full_name, [message_data])
Run Code Online (Sandbox Code Playgroud)

它接受 **attrs 以便将所有关键字参数传递给另一个函数。

目前..我的 queue() 函数不起作用。

如果可能,我如何修复我的queue()函数以将packetdict 参数解压缩为publish()可接受的内容?

谢谢!


编辑:

我收到了一些错误消息。

为了:

def queue(self, packet):
    self.topic.publish(self.message, self.client, **packet)
Run Code Online (Sandbox Code Playgroud)

我得到: TypeError: 1 has type <class 'int'>, but expected one of: (<class 'bytes'>, <class 'str'>)


为了:

def queue(self, packet):
    self.topic.publish(self.message, self.client, packet)
Run Code Online (Sandbox Code Playgroud)

我得到: publish() takes from 2 to 3 positional arguments but 4 were given


为了:

def queue(self, **packet):
    self.topic.publish(self.message, self.client, packet)
Run Code Online (Sandbox Code Playgroud)

我得到: TypeError: queue() takes 1 positional argument but 2 were given


和:

def queue(self, *packet):
    self.topic.publish(self.message, self.client, packet)
Run Code Online (Sandbox Code Playgroud)

我得到: TypeError: publish() takes from 2 to 3 positional arguments but 4 were given


编辑2:

正如@gall 正确建议的那样,这是我发送的数据,解包没有问题。使用此功能:

def queue(self, packet):
    self.topic.publish(self.message, self.client, **packet)
Run Code Online (Sandbox Code Playgroud)

当我只用字符串调用它时它有效:

queue({
        'an_item': '1',
        'a_key': 'value'
    })
Run Code Online (Sandbox Code Playgroud)

谢谢你们!

Jon*_*ler 1

根据publish的文档字符串,attr必须是一个string -> string字典。

您可以通过替换来解决该问题

queue({
    'an_item': 1,
    'a_key': 'value'
})
Run Code Online (Sandbox Code Playgroud)

带有纯字符串参数,例如

queue({
    'an_item': '1',
    'a_key': 'value'
})
Run Code Online (Sandbox Code Playgroud)

看来您的问题与字典解包无关。