Skip to main content
 首页 » 编程设计

python之Python Protocol Buffers 中的 Map Fields 是否有复制构造函数

2025年01月19日36虾米哥

Python Generated Code解释了 protobuf 的大多数用例 map fields在 Python 中,而不是如何将一张 map 复制到另一张 map 。

给定简单 map

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

您不能为嵌入的消息字段分配值,所以没有做:

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

也没有 CopyFrom 的实现因为 map 本身不是消息,所以它是消息中的一个字段。

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

我也无法复制整条消息,因为我只想要 map 。

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

我希望我不必遍历所有键并逐一分配!

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

请您参考如下方法:

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

dst.properties.update(src.properties)