0

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
Sibtain Reza
  • 513
  • 2
  • 14
mikea62
  • 3
  • 1
  • The problem is that you have a newline at the end, and so your split is going to give you three elements, with the final element being the empty string. Use `output.splitlines()` instead. – Frank Yellin Jan 10 '22 at 04:26
  • Related: [Import dictionary from txt file](https://stackoverflow.com/questions/31848590/import-dictionary-from-txt-file) – smci Jan 10 '22 at 05:43

4 Answers4

0

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

Mahamudul Hasan
  • 2,745
  • 2
  • 17
  • 26
0
output = """Port WWN : 10:00:00:00:xx:xx:xx:01
Node WWN : 20:00:00:00:xx:xx:xx:01"""

def Convert(a):
    it = iter(a)
    res_dct = dict(zip(it, it))
    return res_dct

d = [Convert(x.split(' : ')) for x in (output.split("\n"))]
print(d)

->

[{'Port WWN': '10:00:00:00:xx:xx:xx:01'}, {'Node WWN': '20:00:00:00:xx:xx:xx:01'}]
Gab
  • 3,404
  • 1
  • 11
  • 22
0

There are several ways to do this... However, this is the most common:

  1. Using the JSON library:
    JSON is a native library to Python, and it can be very useful in many scenarios... Here is how you would use it in your scenario:
import json
  
# Defining output as the string variable
output = "Port WWN : 10:00:00:00:xx:xx:xx:01\n"
  
# Use "json.loads()"
d = json.loads(output)
  
# print result
print(str(d))
0

You were close. Use splitlines as suggested in comments, and use a regular expression to split each line only once.

dict([re.split(r"\s*\:\s*", line, 1) for line in output.splitlines()])

Outputs:

{'Port WWN': '10:00:00:00:xx:xx:xx:01', 'Node WWN': '20:00:00:00:xx:xx:xx:01'}
Chris
  • 26,361
  • 5
  • 21
  • 42