Reputation: 43
I'y new to writing scripts in Python but I know you can have a list inside a dictionary but can you have a dictionary inside a list?
My example is i'm trying to execute a script on a list of linux servers. I have do it with one dictionary as such (the details are blocked for obvious reasons):
list1 = {
'IP_' : '@IPADDR',
'Username_' : '@USER',
'Password_' : '@PASSWD',
'dirlocation' : '@DIR'
}
and then...
ssh.connect(list1['IP_'], port=22, username=list1['Username_'], password=list1['Password_'])
but is it possible to have something like:
ServerList = {
list1 = {
'IP_' : '@IPADDR',
'Username_' : '@USER',
'Password_' : '@PASSWD',
'dirlocation' : '@DIR'
}
list2 = {
'IP_' : '@IPADDR',
'Username_' : '@USER',
'Password_' : '@PASSWD',
'dirlocation' : '@DIR'
}
}
and then create a loop as such?
for listobj in ServerList:
ssh.connect(ServerList.listobj['IP_'], port=22, username=listobj['Username_'], password=listobj['Password_'])
This is probably what some would see to be a silly question but many thanks for you help!
Upvotes: 2
Views: 141
Reputation: 16556
It's possible. You can either have a dict of dict:
>>> ServerDict = {
...
... 'list1': {
... 'IP_' : '@IPADDR1',
... 'Username_' : '@USER',
... 'Password_' : '@PASSWD',
... 'dirlocation' : '@DIR'
... },
...
... 'list2': {
... 'IP_' : '@IPADDR2',
... 'Username_' : '@USER',
... 'Password_' : '@PASSWD',
... 'dirlocation' : '@DIR'
... }
... }
Or a list:
>>> ServerList = [
...
... {
... 'IP_' : '@IPADDR1',
... 'Username_' : '@USER',
... 'Password_' : '@PASSWD',
... 'dirlocation' : '@DIR'
... },
...
... {
... 'IP_' : '@IPADDR2',
... 'Username_' : '@USER',
... 'Password_' : '@PASSWD',
... 'dirlocation' : '@DIR'
... }
... ]
And you can iterate through the dict
>>> 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
or the list:
>>> for i in ServerList:
... print i['IP_']
...
@IPADDR1
@IPADDR2
Upvotes: 2
Reputation: 727
Yes, it is possible to have a list of dict items:
>>> foo = [ {'a':1,'b':2} , {'c':3,'d':4} ]
>>> foo[1]
{'c': 3, 'd': 4}
>>>
Upvotes: 2