[英]Iterating through a dictionary (hash table) and packing into a struct
我正在用 Python 3 编写程序,我想做的一项任务是获取字典并通过网络发送它(使用 UDP)。 但是由于我无法在不首先将其转换为原始字节数据的情况下通过 UDP 发送字典,因此我决定使用struct
库并将键和值打包到bytearray
。
我想要的结构格式是这样的:
我决定使用struct.pack_into()
函数,因为我想遍历字典中的每个(key, value)
并将它们打包。
到目前为止,这是我的代码示例字典:
import struct
my_dict = {2: 4, 3: 1} # I have 4 entries in this example.
# The length of my_dict is 2; multiply by 2 to get the desired value of 4.
num_entries = 2 * len(my_dict.keys())
# I need to pack "num_entries" itself, then each (key, value) entry.
# I multiply this total by 2 at the end because I need each value to be
# 2 bytes.
# E.g. if num_entries is 2, then I need space to pack the "2", then
# key_one, value_one, key_two, value_two. That's 10 bytes total.
b = bytearray((1 + num_entries) * 2)
for i, (key, value) in enumerate(my_dict.items(), start=1):
struct.pack_into('!2H', b, i, key, value) # Use 'i' as the offset.
print(b)
# Now prepend num_entries (2, in this case) to the top of the struct.
struct.pack_into('!H', b, 0, num_entries)
# Print the final struct.
print(b)
我想要的最终结构输出是这样的:
bytearray(b'\x00\x02\x00\x02\x00\x04\x00\x03\x00\x01')
但是我得到了这个:
struct at this point in the loop: bytearray(b'\x00\x00\x02\x00\x04\x00\x00\x00\x00\x00')
struct at this point in the loop: bytearray(b'\x00\x00\x00\x03\x00\x01\x00\x00\x00\x00')
bytearray(b'\x00\x02\x00\x03\x00\x01\x00\x00\x00\x00') # The final bytearray. key=2, value=4 is not present!
似乎我没有在正确的位置打包到结构中。 我想从my_dict
获取每个key
和value
并打包它们,然后移动到下一个key
和value
并将它们打包在接下来的两个字节中(因此我使用enumerate()
来保持迭代器),依此类推. 请参考上图。 但似乎字节反而被覆盖了。
我做错了什么,我该如何纠正?
我最终找到了另一个解决方案。 我没有使用struct.pack_into()
和enumerate()
,而是调用了bytearray()
的extend()
方法,如下所示:
import struct
my_dict = {2: 4, 3: 1} # I have 2 entries (keys) in this example.
num_entries = len(my_dict.keys())
b = bytearray()
b.extend(struct.pack('!H', num_entries)) # Prepend the number of entries.
for key, value in my_dict.items():
b.extend(struct.pack('!2H', key, value))
# Print the final bytearray.
print(b)
以上给了我所需的输出:
bytearray(b'\x00\x02\x00\x02\x00\x04\x00\x03\x00\x01')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.