开发者

python struct unpack into a dict

开发者 https://www.devze.com 2023-03-29 18:59 出处:网络
struct.unpack will unpack data into a tuple.Is there an equivalent that will store data into a dict instead?

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 t开发者_JAVA百科hrough 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...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号