Python Generated Code在Python语言中解释了protobuf map fields的大多数用例,但没有解释如何将一个地图复制到另一个地图。
给定简单的映射
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)
我也不能复制整个消息,因为我只想要地图。
# Copies unwanted fields!
dst = Dst()
dst.CopyFrom(src)
我希望我不必遍历所有的键并逐个赋值!
# Iterate over map keys
for key in src.properties:
dst.properties[key] = src.properties[key]
发布于 2021-10-19 18:49:45
如果映射的值是简单类型,则dst.properties.update(src.properties)
应该可以工作。但是,如果您有一个带有消息类型值的映射,例如:
message Prop {
optional string value = 1;
optional bool is_public = 2;
}
message Src {
map<string, Prop> properties = 1;
...
}
message Dst {
map<string, Prop> properties = 1;
...
}
然后.update
(或任何类型的直接赋值)将抛出:
ValueError: Direct assignment of submessage not allowed
取而代之的是,你必须这样做:
for k, v in src.properties.items():
dst.properties[k].CopyFrom(v)
发布于 2018-06-02 02:48:07
python protobuf生成的代码中的Map字段的操作非常类似于python dicts,所以您可以使用.update()来复制:
dst.properties.update(src.properties)
https://stackoverflow.com/questions/48672377
复制相似问题