把字符串变成字典

Turn a string into a dictionary

我有一个简单的字符串,我从 API:

IP Address: 8.8.8.8

Country: <country>

State: <state>

City: <city:

Latitude: <Latitude>

Longitude: <Longitude>

但我正试图在字典中转换这个字符串,例如:

{
'IP Address': '8.8.8.8',
'Country': '<country>',
'State': '<state>',
'City': '<city>',
'Latitude': '<Latitude>',
'Longitude': '<Longitude>',
}



尝试:

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)

这将创建并打印字典:

{
    "IP Address": "8.8.8.8",
    "Country": "<country>",
    "State": "<state>",
    "City": "<city>",
    "Latitude": "<Latitude>",
    "Longitude": "<Longitude>",
}