开发者

How to pack a dict into a struct so that I can store it in a file and later unpack it

开发者 https://www.devze.com 2023-02-17 08:52 出处:网络
I have the following code to pack the dictionary into a struct ... 开发者_StackOverflow >>> this = bytearray(2)

I have the following code to pack the dictionary into a struct ...

开发者_StackOverflow
>>> this = bytearray(2)    
>>> this[0] = 100   
>>> this[1] = 150  
>>> bool = True    
>>> str = 'new'  
>>> dct = {'bt_arr': this, 'string':str, 'boolean': bool}  
>>> print dct  
{'bt_arr': bytearray(b'd\x96'), 'boolean': True, 'string': 'new'}  
val = struct.pack ('!' + 'B' +'B' + 'B'*3 + '?', dct['bt_arr'][0], dct['bt_arr'][1],dct['string'][0:3], dct['boolean'])                                                                         
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
struct.error: pack requires exactly 6 arguments

can you kindly let me know what I'm doing wrong in the above code....

I want to unpack it in a similar fashion....


Thanks to martineau and eumiro I got this solution, please let me know if there is a better solution

val = struct.pack ('!' + 'B' +'B' + 'c'*3 + '?', *(tuple(dct['bt_arr'][0:2])+ tuple(dct['string'][0:3]) + (dct['boolean'],)))


There is a problem with missing bracket here:

dct['bt_arr'[1]

EDIT:

val = struct.pack ('!' + 'B' +'B' + 'B'*3 + '?', dct['bt_arr'][0], dct['bt_arr'][1],dct['string'][0:3], dct['boolean'])

This format '!' + 'B' +'B' + 'B'*3 + '?' wants to store five elements, that's why the function needs six arguments (format included). You provide it with four only.

EDIT2:

val = struct.pack('!' + 'B' +'B' + 'B'*3 + '?', *(list(dct['bt_arr']) + list(dct['string'][0:3]) + [dct['boolean']]))
0

精彩评论

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