Python - 列表中是否可以有字典?

标签 python dictionary

我不熟悉用 Python 编写脚本,但我知道你可以在字典中包含一个列表,但是你可以在列表中包含一个字典吗?

我的例子是我正在尝试在 Linux 服务器列表上执行脚本。我已经用一本字典做到了这一点(由于明显的原因,详细信息被屏蔽):

list1 = {
'IP_' : '@IPADDR',
'Username_' : '@USER',
'Password_' : '@PASSWD',
'dirlocation' : '@DIR'
}

然后...

    ssh.connect(list1['IP_'], port=22, username=list1['Username_'], password=list1['Password_'])

但是是否有可能有类似的东西:

ServerList = {

list1 = {
'IP_' : '@IPADDR',
'Username_' : '@USER',
'Password_' : '@PASSWD',
'dirlocation' : '@DIR'
}

list2 = {
'IP_' : '@IPADDR',
'Username_' : '@USER',
'Password_' : '@PASSWD',
'dirlocation' : '@DIR'
}
}

然后创建一个这样的循环?

for listobj in ServerList:
    ssh.connect(ServerList.listobj['IP_'], port=22, username=listobj['Username_'], password=listobj['Password_'])

这可能是有些人认为是一个愚蠢的问题,但非常感谢您的帮助!

最佳答案

这是可能的。你可以有一个字典的字典:

>>> ServerDict = {
...
... 'list1': {
... 'IP_' : '@IPADDR1',
... 'Username_' : '@USER',
... 'Password_' : '@PASSWD',
... 'dirlocation' : '@DIR'
... },
...
... 'list2': {
... 'IP_' : '@IPADDR2',
... 'Username_' : '@USER',
... 'Password_' : '@PASSWD',
... 'dirlocation' : '@DIR'
... }
... }

或者列表:

>>> ServerList = [
...
...  {
... 'IP_' : '@IPADDR1',
... 'Username_' : '@USER',
... 'Password_' : '@PASSWD',
... 'dirlocation' : '@DIR'
... },
...
...  {
... 'IP_' : '@IPADDR2',
... 'Username_' : '@USER',
... 'Password_' : '@PASSWD',
... 'dirlocation' : '@DIR'
... }
... ]

你可以迭代字典

>>> for k,v in ServerDict.items():
...  print k, v['IP_']
...
list1 @IPADDR1
list2 @IPADDR2
>>> for k in ServerDict.keys():
...   print ServerDict[k]['IP_']
...
@IPADDR1
@IPADDR2
>>> for v in ServerDict.values():
...   print v['IP_']
...
@IPADDR1
@IPADDR2

或列表:

>>> for i in ServerList:
...   print i['IP_']
...
@IPADDR1
@IPADDR2

关于Python - 列表中是否可以有字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31324759/

相关文章:

python - 使用openCV分割,裁剪(边界框)和标记字符

python - Pandas cut,如何标记正确的开放端点?

python - subprocess.call 无法将标准输出发送到 ffmpeg

python - __new__ 覆盖不起作用

Ruby 数组数组和 map 方法

ios - 在 UITableView 中从 [(key : String, value: [[String : Any]])] 分配键和值

python - 动态网站通过类名查找元素并使用 Selenium 和 Chrome 执行与 Python 中的类关联的 onclick 方法

angular - ionic 错误地理定位 ionic 未捕获( promise ): TypeError: Object(…) is not a function TypeError: Object(…) is not a function

python - 字典理解 Python

c# - Unity3D连接MySQL报错