python - 解压字典并将其作为关键字参数传递给函数

标签 python python-3.x dictionary google-cloud-pubsub argument-unpacking

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

我有一个函数可以获取 packet作为参数(应该是字典)

def queue(self, packet):
    self.topic.publish(self.message, self.client, **packet)

我这样调用它:

queue({
        'an_item': 1,
        'a_key': 'value'
    })

发布功能,在3rd party 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])

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

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

如果可能的话,我该如何修复我的 queue()函数解压 packet将参数听写成某种东西 publish()会接受吗?

谢谢!


编辑:

我收到一些错误消息。

对于:

def queue(self, packet):
    self.topic.publish(self.message, self.client, **packet)

我得到: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)

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


对于:

def queue(self, **packet):
    self.topic.publish(self.message, self.client, packet)

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


和为了:

def queue(self, *packet):
    self.topic.publish(self.message, self.client, packet)

我得到: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)

当我只用字符串调用它时它起作用了:

queue({
        'an_item': '1',
        'a_key': 'value'
    })

谢谢大家!

最佳答案

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

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

queue({
    'an_item': 1,
    'a_key': 'value'
})

使用纯字符串参数,例如

queue({
    'an_item': '1',
    'a_key': 'value'
})

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

关于python - 解压字典并将其作为关键字参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45014657/

相关文章:

java - 序列不向上计数

python - 我如何从列表(每个索引独立) - 在字典中 - 写入条目列表?

c# - 字典的匿名集合初始值设定项

python - 如何通过 SqlAlchemy 中的 joinloaded 表进行过滤?

python - NetworkX From_Pandas_dataframe

python - 删除两个集合中的公共(public)字符串元素python3

python - 使用矩阵第一行的值作为 matplotlib.pyplot.imshow 的刻度

python - 列表切片并找到第二大值python

python - 使用opencv加载32位整数图像

python - 如何在 python 中将目录结果转换为 csv 或 json?