使用两个字典键(key 1 _and_ 2)来确定值

Using two dictionary keys (key 1 _and_ 2) to determine value

我有一个 Python 脚本,可以从预先存在的二进制文件中读取两个字节。一个字节确定设备类型,下一个字节确定子设备类型。两者共同定义了整个设备。

例如:

x41 and x01 = Printer
x43 and x01 = Audio Device

例如,我的代码需要找到 x41 和 x01 才能有打印机。

我想过用字典来做这件事,但我认为这意味着每个值有两个键,而且实现起来并不那么简单(至少对我的技能而言)。

字典是个好方法吗?或者别的东西会更好吗?

使用单级字典表示此数据有利也有弊。然而,实现是微不足道的:使用元组作为字典键。

d = { (0x41,0x01) : "Printer", (0x43,0x01) : "Audio Device" }
print "The device is:", d[major_byte,minor_byte]

作为替代方案,您可以使用嵌套字典:

d = { 0x41 : { 0x01 : "Printer" }, 0x43 : { 0x01 : "Audio Device" } }
print "The device is:", d[major_byte][minor_byte]

您要使用哪一个取决于您的具体要求。

正如评论中所说,有两种可能的方法:

Devices={(0x41,0x01) : 'Printer' , (0x43,0x01) : 'Audio Device', ...}

ComputerDevices={ 0x41 : 'Printer' , 0x43 : 'Audio Device', ...}
KitchenDevices={ 0x41 : 'Roaster' , 0x26 : 'Oven', ...}
...
Devices = {0x01: ComputerDevices , 0x02 :KitchenDevices, ...}

您还可以连接字节:key =bytes([0x43,0x01]) 并将其用作字典键。