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 ,
         "Node WWN" : 20:00:00:00:xx:xx:xx:01


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


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/", line 6, in <module>
    d = dict(x.split("=") for x in output.split("\n"))
ValueError: dictionary update sequence element #0 has length 1; 2 is required


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"))


sample output:
enter image description here

Answered By – Mahamudul Hasan

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More