我試圖將以下字符串轉換爲字典,其中IP成爲一個鍵,以及其他所有內容|成爲一個值:如何將字符串轉換爲字典在python中轉義特殊字符
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"}'
並使用此代碼先sp點燃行:
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。
這工作和很簡單。閱讀某處,分裂是在新的線人物分裂......一定是在做夢。猜猜是時候休息一下了。 – Lidia