Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python struct unpack into a dict

Tags:

python

unpack

struct.unpack will unpack data into a tuple. Is there an equivalent that will store data into a dict instead?

In my particular problem, I am dealing with a fixed-width binary format. I want to be able, in one fell swoop, to unpack and store the values in a dict (currently I manually walk through the list and assign dict values)

like image 696
Foo Bah Avatar asked Aug 23 '11 01:08

Foo Bah


3 Answers

If you're on 2.6 or newer you can use namedtuple + struct.pack/unpack like this:

import collections
import struct

Point = collections.namedtuple("Point", "x y z")

data = Point(x=1, y=2, z=3)

packed_data = struct.pack("hhh", *data)
data = Point(*struct.unpack("hhh", packed_data))

print data.x, data.y, data.z
like image 112
PabloG Avatar answered Oct 17 '22 11:10

PabloG


Do you want something like this?

keys = ['x', 'y', 'z']
values = struct.unpack('<III', data)
d = dict(zip(keys, values))
like image 8
FogleBird Avatar answered Oct 17 '22 09:10

FogleBird


The struct documentation shows an example of unpacking directly into a namedtuple. You can combine this with namedtuple._asdict() to get your one swell foop:

>>> import struct
>>> from collections import namedtuple
>>> record = 'raymond   \x32\x12\x08\x01\x08'
>>> Student = namedtuple('Student', 'name serialnum school gradelevel')
>>> Student._asdict(Student._make(struct.unpack('<10sHHb', record)))
{'school': 264, 'gradelevel': 8, 'name': 'raymond   ', 'serialnum': 4658}
>>> 

If it matters, note that in Python 2.7 _asdict() returns an OrderedDict...

like image 6
mtrw Avatar answered Oct 17 '22 11:10

mtrw