How do I split a string into a dictionary?

0

Issue

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

tried:

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

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 <module>
    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

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