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

标签 python python-2.7 python-2.x

我正在尝试将以下字符串转换为字典,其中 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/

相关文章:

Python 编程 : Multiline Comments before an Else statement

python - 连接 2 个数据框并创建父子关系?

python - Django 1.7 - 我如何抑制 "(1_6.W001) Some project unittests may not execute as expected."?

python - 如何匹配 *仅* 六位数版本?

python - 如何修复 "AttributeError: module ' tensorflow' 没有属性 'get_default_graph'“?

python - 按字典值对字典的嵌套列表进行排序

求矩阵转置的Python代码

python-2.7 - kibana不加载时间序列数据

python - 使用Python请求库进行API GET请求

python - 深度复制后时间戳的 ruamel.yaml 格式似乎已损坏