Issue
I'm trying to convert the following string into a dictionary, where IP becomes a key, and everything else after | becomes a value:
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"}'''
This is the code I tried:
d = dict(node.split('|') for node in my_string.split())
However, I get this error:
ValueError: dictionary update sequence element #1 has length 1; 2 is required
So I simplified my_string to just one line:
my_string = '10.11.22.33|{"property1": "0", "property2": "1", "property3": "1", "property4": "1", "property5": "0"}'
And used this code to first split the line:
wow = my_string.split('|')
output:
['10.11.22.33', '{"property1": "0", "property2": "1", "property3": "1", "property4": "1", "property5": "0"}']
The above is a list of two elements. However, when I try to create dictionary out of it, it fails with this error:
d = dict(wow)
output:
ValueError: dictionary update sequence element #0 has length 11; 2 is required
I do not want to modify the value - it needs to be preserved as is. What is the proper way to get this line into a dictionary so that it looks like this:
{'10.11.22.33': '{"property1": "0", "property2": "1", "property3": "1", "property4": "1", "property5": "0"}'}
This is Python 2.6.
Solution
Your first approach is correct except that it splits at the wrong places because str.split()
uses whitespace as the separator character by default. Try str.splitlines()
instead:
d = dict(node.split('|') for node in my_string.splitlines())
Answered By - Selcuk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.