A dictionary is a list of items with key and value pairs. The best way to describe it is by using examples. Let's start:
- To declare a key–value pair of the host and IP, enter the following (for example):
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.100'}
- To add a new item to a dictionary, do the following:
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.101'}
hosts_dictionary['Srv-003'] = '10.0.0.103'
print hosts_dictionary
- To update an existing item in a dictionary, do the following:
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.101'}
hosts_dictionary['Srv-002'] = '10.0.0.122'
print hosts_dictionary
- To delete an existing item in a dictionary, do the following:
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.101'}
del hosts_dictionary['Srv-002']
print hosts_dictionary
- To iterate through a dictionary, do the following:
hosts_dictionary = { 'Srv-001':'10.0.0.100', 'Srv-002':'10.0.0.101'}
for host,ip in hosts_dictionary.items(): print "host:%s , IP: %s" % (host,ip)