-3

我正在尝试从字符串创建字典。字符串是 =

              """SSID 1                  : Something    
                 Network type            : Infrastructure    
                 Authentication          : WPA2-Personal    
                 Encryption              : CCMP"""

我希望输出为

{"ssid 1": "something", "Network type" : "Infrastructure", "Authentication": "WPA2-Personal", "Encryption": "CCMP"}
4

2 回答 2

4
output = {}
for entry in input.split("\n"):
    tokens = [token.strip() for token in entry.split(":")]
    output[tokens[0]] = tokens[1]

请注意,如果您有:任何键或值,这将中断,但对于您提供的非常简单的示例,我认为它会起作用。

于 2019-10-28T06:32:21.237 回答
1

你可以像这样使用字典理解

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'}
于 2019-10-28T07:35:47.720 回答