I have an input file as below, from which I can construct my dictionary
General format
<IP_1>
KEY_1=VALUE_1
KEY_2=VALUE_2
<IP_2>
KEY_1=VALUE_1
KEY_2=VALUE_2
Example
192.168.1.1
USER_NAME=admin
PASSWORD=admin123
192.168.1.2
USER_NAME=user
PASSWORD=user123
Expected dictionary should look like this:
>>print dictionary_of_ip
{'192.168.1.1':{'USER_NAME'='admin','PASSWORD'='admin123'},
'192.168.1.2':{'USER_NAME'='user','PASSWORD'='user123'}}
Essentially a dictionary within dictionary
Below is my code:
def generate_key_value_pair(filePath, sep='='):
dict_of_ip = {}
slave_properties = {}
with open(filePath, "rt") as f:
for line in f:
stripped_line = line.strip()
if stripped_line and stripped_line[0].isdigit():
#print 'Found Ip'
ip = stripped_line
dict_of_ip[ip] = ''
elif stripped_line and stripped_line[0].isupper():
#print "Found attributes")
key_value = stripped_line.split(sep)
key = key_value[0].strip()
value = key_value[1].strip()
slave_properties[key] = value
dict_of_ip[ip] = slave_properties
return dict_of_ip
I am able to get the first of IP and their attributes as expected, but the second set of values from second IP are overwriting the first one.
>>print dict_of_ip
{'192.168.1.1': {'USER_NAME': 'user', 'PASSWORD': 'user123'},
'192.168.1.2': {'USER_NAME': 'user', 'PASSWORD': 'user123'}}
dict_of_ip[ip] = slave_properties
is causing the overwrite. How do I prevent the values from the '192.168.1.2'
key overwriting the first one?