I have an input file, as shown below, from which I can build a 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
The 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 in a 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():
ip = stripped_line
dict_of_ip[ip] = ''
elif stripped_line and stripped_line[0].isupper():
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 can get the first of the IP and their attributes as expected, but the second set of values from the second IP address overwrites the first.
>>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_propertiescauses overwriting. How to prevent the replacement of values from the '192.168.1.2'first key ?
source
share