2

i would like help to convert byte to dictionnary, i have;

received message: b'req:21;num:54771377;INFO:;GATE:N;'

i would like

d1 = {'req':21,'num':54771377,'INFO':,'GATE':N}

thank you

1
  • hello, what did you done to make this? Can you please show us some code. Commented Nov 9, 2016 at 14:25

2 Answers 2

1

Do that with a gencomp piped into a dictionary (drop the empty fields). Split according to semicolon after having converted the bytes to string (assumption: data inside the bytes object is ASCII)

s = b"req:21;num:54771377;INFO:;GATE:N;"
d = dict(toks.split(":") for toks in s.decode("ascii").split(";") if toks)

print(d)

result:

{'INFO': '', 'GATE': 'N', 'req': '21', 'num': '54771377'}

notes:

  1. a dictcomp would be tempting like this d = {toks.split(":")[0] : toks.split(":")[1] for toks in s.decode("ascii").split(";") if toks} but it would mean that you split twice as too many on colon

  2. if you have non-ascii data, you can still do the job, but the data will remain as bytes: d = dict(toks.split(b":") for toks in s.split(b";") if toks)

Sign up to request clarification or add additional context in comments.

Comments

1

Something like this?

str = b'req:21;num:54771377;INFO:;GATE:N;'.decode("ascii") 
arr = str.split(';')[::-1]
arr = [x.split(':') for x in arr if x != '']
return dict(arr)

Result:

{u'INFO': u'', u'GATE': u'N', u'num': u'54771377', u'req': u'21'}

Repl: https://repl.it/X3G/8284

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.