[英]Python Dictionary multiple values per key
我正在尝试迭代字典,并将多个值分配给一个键。 像这样:
devices = {'device_ip':('10.1.1.1','10.1.1.2','10.1.1.3'),
'device_hostname':('sw1','sw2','sw3')}
我然后尝试将IP和Hostname值传递到这样的事情:
scp_command = 'sshpass -p 123 scp -o StrictHostKeyChecking=no cisco@' + devices['device_ip'] + ':startup.cfg ' + devices['device_hostname'] + filename
我不想要的是修改每个IP /主机名对的scp_command
并重新使用此变量以在代码中具有最少量的行。
如何为每个key-value
对分配一个list
?
devices = {'device_ip':['10.1.1.1','10.1.1.2','10.1.1.3'],
'device_hostname':['sw1','sw2','sw3']}
使用: devices['device_ip'][<index>]
正如我在评论中已经提到的,我会寻求不同的数据结构:
devices = {'sw1':'10.1.1.1',
'sw2':'10.1.1.2',
'sw3':'10.1.1.3'}
要构建你的scp_command
字符串,我建议使用str.format
,例如:
scp_command = 'sshpass -p 123 scp -o StrictHostKeyChecking=no cisco@{ip}:startup.cfg {host} {file}'
cfg_file='example.cfg'
for device in devices:
print(scp_command.format(ip=devices[device], host=device, file=cfg_file))
这样你就可以在你的字符串中引入占位符{}
,它将被.format()
替换为你当前的数据。 结果:
sshpass -p 123 scp -o StrictHostKeyChecking=no cisco@10.1.1.1:startup.cfg sw1 example.cfg
sshpass -p 123 scp -o StrictHostKeyChecking=no cisco@10.1.1.2:startup.cfg sw2 example.cfg
sshpass -p 123 scp -o StrictHostKeyChecking=no cisco@10.1.1.3:startup.cfg sw3 example.cfg
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.