I have a simple string that I got from an API:
IP Address: 8.8.8.8
Country: <country>
State: <state>
City: <city:
Latitude: <Latitude>
Longitude: <Longitude>
But i'm trying to turn this string in a dictionary like:
{
'IP Address': '8.8.8.8',
'Country': '<country>',
'State': '<state>',
'City': '<city>',
'Latitude': '<Latitude>',
'Longitude': '<Longitude>',
}
CodePudding user response:
Try:
out = {}
with open("your_file.txt", "r") as f_in:
for line in map(str.strip, f_in):
if not line:
continue
k, v = line.split(":", maxsplit=1)
out[k.strip()] = v.strip()
print(out)
this creates and prints the dictionary:
{
"IP Address": "8.8.8.8",
"Country": "<country>",
"State": "<state>",
"City": "<city>",
"Latitude": "<Latitude>",
"Longitude": "<Longitude>",
}