传递字典键作为变量名称在python中不起作用

时间:2017-02-15 11:16:20

标签: python dictionary

我想在字典中使用“key”作为变量名。

>> 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'

这里,变量名port1的值= 2.如果我尝试使用print(virsh_out1 [port1]),它会抛出KeyError,而同样的东西适用于print(virsh_out1 [2])。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

将字符串app.use(require('cookie-parser')()); app.get('/a', function (req, res) { console.log(req.cookies); res.cookie('aaa', 'bbb'); res.send('something'); }); app.post('/b', function (req, res) { console.log(req.cookies); res.cookie('ccc', 'ddd'); res.send('something'); }) 转换为port1

int