Dictionary acting weird, and how to pack into binary
I have the code
from struct import pack
self.data = {'SYNC' : 0x16, 'SOH' : 0x01,
'FnCode' : 0x55, 'pacingState' : 0,
'pacingMode' : 6, 'hysteresis' : 0,
'hysteresisInterval' : 300, 'lowrateInterval' : 1000,
'vPaceAmp' : 3500, 'vPaceWidth' : 4,
'VRP' : 320, 'spare' : '\x00\x00\x00\x00\x00'}
print(self.data.keys())
print(self.data.values())
pack('BBBBBBHHHHH5s', self.data.values())
I get the output,
dict_keys(['pacingState', 'SYNC', 'hysteresis', 'FnCode', 'spare', 'lowrateInterval', 'vPaceWidth', 'VRP', 'SOH', 'pacingMode', 'hysteresisInterval',开发者_开发百科 'vPaceAmp'])
dict_values([0, 22, 0, 85, '\x00\x00\x00\x00\x00', 1000, 4, 320, 1, 6, 300, 3500])
Why arent values in the order that I wrote them in in the dictionary (and how can I get them in order)?
Also when i try to do the pack function, i says that pack needs 12 arguments, and data.values has 12 values so Im not sure why its giving me an error.
I tried making a dict with a reference to an array that contained the values(so I could pass the array in since it's in the right order), but changing the dictionary values didnt affect the actual value array it was referencing so that idea is out...
Thanks in advance.
- Dictionaries are unordered. Well, they don't suddenly re-order when they feel like it, but they don't preserve order of insertion or are sorted or anything. Always treat them as if order was random. You can use
collections.OrderedDict
(or if you use an old version that doesn't have them in the standard library, there are various implementations all over the internet). Or maybe you can just use alist
of the values (assuming you don't need the keys and only use them for documentation), which is ordered. - Concerining pack needing 12 arguments: You only give it one argument,
data.values()
. That's one argument, even though it happen to be a collection of 12 objects. Usepack(... ,*data.values())
to unpack the sequence of length 12 into 12 seperate arguments.
Dictionaries do not maintain insertion order of keys, as they are hash tables and do not keep track of key insertion order. If you need an ordered dictionary, Python 2.7 and 3.1 has collections.OrderedDict
. If you are using an older Python version, check out this ActiveState recipe.
As to why your pack
is complaining - you are not actually passing it 12 arguments (as long as your format string is), you are passing it a single argument which is a list.
edit delnan's post shows you how to unpack your values.
精彩评论