Darth Vader
Darth Vader

Reputation: 161

How to import a small text file as a dictionary in python 3

For a python project I have a text file called clues.txt which looks like this:

A#
M*
N%

And in python I am trying to read it in as a dictionary so it forms a dictionary looking like this:

clues_dict = {'A':'#', 'M':'*', 'N':'%'}

The code I'm trying to get to work at the moment is this:

    clues_dict = {}

    with open("clues.txt", "r") as f:
        for line in f:
            for line in f:
                (key, val) = line.split()
                clues_dict[key] = val

    print(clues_dict)

However I get this error:

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

Any help would be gratefully appreciated

Upvotes: 0

Views: 65

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

str.split() splits on a character. You don't have that.

(key, val) = tuple(line.rstrip())

Upvotes: 1

Related Questions