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)
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
Do you want something like this?
keys = ['x', 'y', 'z']
values = struct.unpack('<III', data)
d = dict(zip(keys, values))
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
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With