python struct unpack into a dict

Foo Bah picture Foo Bah · Aug 23, 2011 · Viewed 15.4k times · Source

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)

Answer

PabloG picture PabloG · Aug 23, 2011

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