Dictionary in protocol buffers

Is there any way to serialize a dictionary using protocol buffers, or I'll have to use Thrift if I need that?


Solution 1:

For future answer seekers, ProtoBuf now supports Maps natively:

message MapMessage
{
    map<string, string> MyMap = 1;
}

Solution 2:

Protobuf specification now supports dictionaries (maps) natively.

Original answer

People typically write down the dictionary as a list of key-value pairs, and then rebuild the dictionary on the other end.

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

message Dictionary {
   repeated Pair pairs = 1;
}

Solution 3:

You can check the ProtoText package.

Assume you want to serialize a dict person_dict to a pre-defined PersonBuf protobuf object defined in personbuf_pb2 module.

In this case, to use ProtoText,

import ProtoText
from personbuf_pb2 import PersonBuf

obj = PersonBuf()
obj.update(person_dict)