Skip to content

Instantly share code, notes, and snippets.

@typhoonzero
Last active August 11, 2017 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save typhoonzero/1635a60b5a6e4a507afd7af1b623b4ca to your computer and use it in GitHub Desktop.
Save typhoonzero/1635a60b5a6e4a507afd7af1b623b4ca to your computer and use it in GitHub Desktop.
parse python dict to protobuf message
def parse_list(values, message):
if isinstance(values[0], dict):
for v in values:
cmd = message.add()
parse_dict(v, cmd)
else:
message.extend(values)
def parse_dict(values, message):
for k, v in values.iteritems():
if isinstance(v, dict):
parse_dict(v, getattr(message, k))
elif isinstance(v, list):
parse_list(v, getattr(message, k))
else:
setattr(message, k, v)
def dict_to_protobuf(value, message):
parse_dict(value, message)
proto_msg = YourProtoMessage()
dict_to_protobuf(kwargs, proto_msg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment