Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字符串创建dict(字典)_Python_Python 3.x - Fatal编程技术网

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'}