簡體   English   中英

如何將字符串轉換為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。

您需要先在\\nsplit字符串:

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

您也可以看看re.findall

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

s是您的字符串

您的第一種方法是正確的,但是它會在錯誤的位置分割,因為默認情況下str.split()使用空格作為分隔符。 嘗試使用str.splitlines()代替:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM