Python Protobuf词典列表

Python Protobuf词典列表,python,dictionary,protocol-buffers,grpc,proto,Python,Dictionary,Protocol Buffers,Grpc,Proto,我正在尝试在.proto中定义词典列表 我发现的所有示例都提供了一个具有单个键和值对的字典: message Pair { string key = 1; string value = 2; } message Dictionary { repeated Pair pairs = 1; } 或者类似于: message Dictionary { message Pair { map<string, string> values = 1;

我正在尝试在.proto中定义词典列表

我发现的所有示例都提供了一个具有单个键和值对的字典:

message Pair {
   string key = 1;
   string value = 2;
}

message Dictionary {
   repeated Pair pairs = 1;
}
或者类似于:

message Dictionary {
    message Pair {
        map<string, string> values = 1;
    }
    repeated Pair pairs = 1;
}
更复杂的是,一旦我定义了混合值字典,我需要创建一个消息,它是这些字典的列表。我假设这与创建另一条嵌套字典的重复消息一样简单:

message DictList {
    repeated Dictionary dlist = 1;
}

我想出了几个主意:

  • 似乎应该可以(如果您预先知道所有值类型)使用
    of
    中的一种来表示值()。那可以解决问题,例如
  • 但是,您不能在
    oneof
    中使用
    map
    repeated

  • 您可以使用可选字段,并在消息定义中将它们全部定义为值。然后只设置那些,你实际使用的

  • 您可以使用包装器或已知类型,例如
    Value

  • 编辑 对于
    ,可以这样使用:

    map<string, google.protobuf.Value> dict = 1;
    
    map dict=1;
    
  • 使用
    struct
    (如for_stack所建议),可在此处看到:

  • 您可以尝试
    google.protobuf.Struct
    。无法在oneofOh中定义两次值,您是对的,抱歉。所以在这个上下文中,它与使用可选字段基本相同。它仍然可用,但很难看。:/因此,最好使用for_stack建议的struct。这可能会有帮助:更新答案。
    message Value {
        oneof oneof_values {
            string svalue = 1;
            int ivalue = 2;
            ...
        }
    }
    
    message Pair {
       string key = 1;
       Value value = 2;
    }
    
    message Dictionary {
       repeated Pair pairs = 1;
    }
    
    map<string, google.protobuf.Value> dict = 1;