Reputation: 31
i have a dict of the form :
a = {(7, 190, 0): {0: 0, 1: 10, 2: 10, 3: 37, 4: 45, 5: 49, 6: 69, 7: 45, 8: 130, 9: 59}}
and am trying to write this to a file in binary format. Currently am using python 2.3
I tried using struct module on a simple list and it looks like it can work but when i move on to the dict, it throws an error saying required argument is not an integer. What will be a good way to tackle this? I tried sth like this:
packed_d=[]
for ssd,(add_val) in a.iteritems():
pack_d=struct.pack('BHB',ssd)
packed_data.append(pack_d)
This is where it threw the error..
Any suggestions?
Edited : cool, thats what i was missing, Janne. I tried the following and it looks like its working and was able to unpack as well just to check if it was all ok. Do you think this is a good way to do it? Thanks!
data = {(7, 190, 0): {0: 0, 1: 101, 2: 7, 3: 0, 4: 0}}
packed_data=[]
for ssd,add_val in data.iteritems():
pack_d=struct.pack('BHB', *ssd)
packed_data.append(pack_d)
for add,val in data[ssd].iteritems():
pack_t=struct.pack('BH', add,val)
packed_data.append(pack_t)
packed_data = ['\x07\x00\xbe\x00\x00', '\x00\x00\x00\x00', '\x01\x00e\x00', '\x02\x00\x07\x00', '\x03\x00\x00\x00', '\x04\x00\x00\x00']
Upvotes: 0
Views: 3306
Reputation: 172339
You are giving struct the 'BHB' format, saying that you should have three arguments, an unsigned char, an unsigned short and then another unsigned char.
But you pass in only one argument. And that argument is not an integer, but a tuple of integers.
This works (tested in Python 2.3 to 3.3):
import struct
a = {(7, 190, 0): {0: 0, 1: 10, 2: 10, 3: 37, 4: 45, 5: 49, 6: 69, 7: 45, 8: 130, 9: 59}}
packed_data=[]
for ssd in a:
packed_data.append(struct.pack('BHB', *ssd))
print(packed_data)
Or also:
for a, b, c in a:
packed_data.append(struct.pack('BHB', a, b, c))
In later versions of Python you instead get the error that you didn't have enough parameters, which may be more helpful in this case.
Upvotes: 1
Reputation: 25207
ssd
is a tuple. Unpack it to individual arguments by adding an asterisk in front:
struct.pack('BHB', *ssd)
Upvotes: 1