gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:42:59 26 4
gpt4 key购买 nike

我是用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com