Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I split a string into a dictionary?

Trying to split into a dictionary:

output = "Port WWN : 10:00:00:00:xx:xx:xx:01\n"
"Node WWN : 20:00:00:00:xx:xx:xx:01\n"

tried:
d = dict(x.split(": ") for x in output.split("\n"))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

print(d)


expected output = {Port WWN : 10:00:00:00:xx:xx:xx:01, Node WWN : 20:00:00:00:xx:xx:xx:01}

getting error:

File "/Users/mike/PycharmProject/pyTest/venv/scratch.py", line 6, in
d = dict(x.split("=") for x in output.split("\n"))
ValueError: dictionary update sequence element #0 has length 1; 2 is required

>Solution :

i think it will solve your issue:

output = "Port WWN : 10:00:00:00:xx:xx:xx:01\nNode WWN : 20:00:00:00:xx:xx:xx:01\n"

d = dict(x.split(": ") for x in output.strip().split("\n"))

print(d)

sample output:
enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading