-1
我想在字典中使用「鍵」作爲變量名。傳遞字典鍵作爲變量名在Python中不起作用
>> print(port1)
2
>> print(virsh_out1)
{1: 'tap5be16f98-d3 bridge qbr5be16f98-d3 virtio fa:16:3e:0c:70:bf', 2: 'tap1685f051-29 bridge qbr1685f051-29 virtio fa:16:3e:b8:63:49', 3: 'tap54de7c68-a4 bridge qbr54de7c68-a4 virtio fa:16:3e:f5:c4:7a', 4: 'tap5b857c99-7c bridge qbr5b857c99-7c virtio fa:16:3e:a0:64:dc', 5: 'tap7104dac4-6b bridge qbr7104dac4-6b virtio fa:16:3e:fd:d3:ab', 6: 'tap0a3f7a0e-60 bridge qbr0a3f7a0e-60 virtio fa:16:3e:dd:50:35'}
>> dir(virsh_out1)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
>> print(virsh_out1[2])
tap1685f051-29 bridge qbr1685f051-29 virtio fa:16:3e:b8:63:49
>> print(virsh_out1[port1])
*** KeyError: '2'
這裏,變量名端口1的值= 2。如果我嘗試使用打印(virsh_out1 [端口1]),它拋出KeyError異常,而同樣的事情與印刷工程(virsh_out1 [2])。有人可以幫忙嗎?
端口1是一個海峽,但你需要一個int – BlackBear
非常感謝。我將它轉換爲整數並且工作。 – user3050091