如何将字符串转换为转义 python 中特殊字符的字典

How to convert string into a dict escaping special characters in python

我正在尝试将以下字符串转换为字典,其中 IP 成为键,| 之后的所有其他内容变成一个值:

my_string = '''10.11.22.33|{"property1": "0",     "property2": "1", "property3":     "1", "property4": "1", "property5": "0"}
10.11.22.34|{"property1": "0",     "property2": "0", "property3":     "1", "property4": "1", "property5": "0", "property6": "0", "property7": "1", "property8": "0", "property9": "0", "property10": "1"}'''

这是我试过的代码:

d = dict(node.split('|') for node in my_string.split())

但是,我得到这个错误:

ValueError: dictionary update sequence element #1 has length 1; 2 is required

所以我将 my_string 简化为一行:

my_string = '10.11.22.33|{"property1": "0",     "property2": "1", "property3":     "1", "property4": "1", "property5": "0"}'

并使用此代码首先拆分行:

wow = my_string.split('|')

输出:

['10.11.22.33', '{"property1": "0",     "property2": "1", "property3":     "1", "property4": "1", "property5": "0"}']

以上是两个元素的列表。但是,当我尝试从中创建字典时,它失败并出现此错误:

d = dict(wow)

输出:

ValueError: dictionary update sequence element #0 has length 11; 2 is required

我不想修改该值 - 它需要按原样保留。将此行放入字典的正确方法是什么,使其看起来像这样:

{'10.11.22.33': '{"property1": "0",     "property2": "1", "property3":     "1", "property4": "1", "property5": "0"}'}

这是Python 2.6.

你的第一种方法是正确的,除了它在错误的地方分裂,因为 str.split() uses whitespace as the separator character by default. Try str.splitlines() 而不是:

d = dict(node.split('|') for node in my_string.splitlines())

您需要先 split 您的字符串 \n

dict(ip.split('|') for ip in s.split('\n'))

你也可以看看 re.findall:

dict(re.findall(r'(\d+\.\d+\.\d+\.\d+\d+).*?(\{.*?\})', s))

其中 s 是您的字符串