Python 从字符串创建dict(字典)
我正在尝试从字符串创建字典。 字符串为=Python 从字符串创建dict(字典),python,python-3.x,Python,Python 3.x,我正在尝试从字符串创建字典。 字符串为= """SSID 1 : Something Network type : Infrastructure Authentication : WPA2-Personal Encryption : CCMP""
"""SSID 1 : Something
Network type : Infrastructure
Authentication : WPA2-Personal
Encryption : CCMP"""
我希望输出为
{"ssid 1": "something", "Network type" : "Infrastructure", "Authentication": "WPA2-Personal", "Encryption": "CCMP"}
请注意,如果您在任何键或值中都有一个:这将中断,但对于您提供的非常简单的示例,我认为它会起作用。您可以像这样使用dict理解
data = """
SSID 1 : Something
Network type : Infrastructure
Authentication : WPA2-Personal
Encryption : CCMP"""
dct = {key: value
for line in data.split("\n") if line
for splitted in [line.split(" : ")] if len(splitted) == 2
for key, value in [map(str.strip, splitted)]}
print(dct)
这就产生了
{'SSID 1': 'Something', 'Network type': 'Infrastructure',
'Authentication': 'WPA2-Personal', 'Encryption': 'CCMP'}
你可以用“:”来分开,这样就不太可能了,用听写理解代替。然而,+1。
{'SSID 1': 'Something', 'Network type': 'Infrastructure',
'Authentication': 'WPA2-Personal', 'Encryption': 'CCMP'}