我正在尝试将以下字符串转换为字典,其中 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。
最佳答案
您需要先在 \n
上拆分
您的字符串:
dict(ip.split('|') for ip in s.split('\n'))
你也可以看看 re.findall
:
dict(re.findall(r'(\d+\.\d+\.\d+\.\d+\d+).*?(\{.*?\})', s))
s
是你的字符串
关于python - 如何将字符串转换为字典转义python中的特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35353933/