Python Protocol Buffers中是否有Map字段的复制构造函数?

2024-09-30 06:14:50 发布

您现在位置:Python中文网/ 问答频道 /正文

Python Generated Code解释Python中protobufmap fields的大多数用例,但不解释如何将一个映射复制到另一个映射。在

给定简单地图

message Src {
    map<string, string> properties = 1;
    ...
}

message Dst {
    map<string, string> properties = 1;
    ...
}

无法为嵌入的消息字段赋值,因此无法执行以下操作:

^{pr2}$

也没有CopyFrom的实现,因为映射本身不是消息,而是消息中的字段。在

# Will not work.
dst = Dst()
dst.properties.CopyFrom(src.properties)

我也不能复制整个信息,因为我只想要地图。在

# Copies unwanted fields!
dst = Dst()
dst.CopyFrom(src)

我希望我不必迭代所有的键并逐个分配!在

# Iterate over map keys
for key in src.properties:
    dst.properties[key] = src.properties[key]

Tags: keysrc消息mapmessagefieldsstring地图
1条回答
网友
1楼 · 发布于 2024-09-30 06:14:50

python protobuf生成的代码中映射字段的操作与python dicts非常相似,因此可以使用.update()复制:

dst.properties.update(src.properties)

相关问题 更多 >

    热门问题