-2

I am trying to transform a file to dictionary but having error.

def txt_to_dict():
    dict = {}
    with open("GEO_human.gaf") as f:
        for line in f:
            (key, val) = line.split(":")
            dict[(key)] = val
        print dict
txt_to_dict()

This is my error

(key, val) = line.split(":") ValueError: need more than 1 value to unpack

GEO_human.gaf

6
  • If you save your file something like this f.write(json.dumps(your_dict)). To open and read: with open("your_file") as f: d = json.load(f) Commented Mar 29, 2019 at 15:06
  • 1
    Are you sure that every line looks like "blah:yada"? Commented Mar 29, 2019 at 15:06
  • 2
    The error is clear, your file isn't well formatted Commented Mar 29, 2019 at 15:07
  • 1
    Show the GEO_human.gaf content Commented Mar 29, 2019 at 15:09
  • @Colin, no it is not but as I mentioned from bottom, I am so new in python so I am not sure what should I do. Commented Mar 31, 2019 at 11:38

2 Answers 2

0

Use Json library:

To save dict into file

with open("your_file") as f:
    f.write(json.dumps(your_dict))

To load dict from file

with open("your_file") as f:
    d = json.load(f)
Sign up to request clarification or add additional context in comments.

Comments

0

Probably there are more than one ':' in a line. You can try:

(key, val) = line.split(":", 1)

this code splits the line at the first ':'.

1 Comment

I tried but still have same problem but thanks for your help :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.