Kef
Kef

Reputation: 73

Python convert byte array to dictionary

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

Upvotes: 2

Views: 9898

Answers (2)

Leonardo Paglialunga
Leonardo Paglialunga

Reputation: 338

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

Upvotes: 1

Jean-François Fabre
Jean-François Fabre

Reputation: 140178

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)

Upvotes: 1

Related Questions