Dave W
Dave W

Reputation: 21

Trying to write a dictionary from file, key becomes value

I have an assessment where I have to write a full name with a score to a file, then read it back and be able to sort by either name or high score. I've worked out how to read the file into a dictionary using:

d = {}
with open("Dr Welch.txt") as f:
    d = dict(line.strip().split(None, 1) for line in f)
print(d)

But it writes the dictionary like this:

{'Cammy': 'MEele 4', 'Amy': 'Jones   10', 'Dave': 'Wright 5'}

When the second part of the name is supposed to be a part of the key, not the value.

Upvotes: 2

Views: 74

Answers (3)

Mike Müller
Mike Müller

Reputation: 85482

Use .rsplit() to split off the number which is on the right:

d = dict(line.strip().rsplit(None, 1) for line in f)

You can also use a dictionary comprehension to convert the scores to int:

with open("Dr Welch.txt") as f:
    d = {k: int(v) for k, v in (line.rsplit(None, 1) for line in f)}
print(d)

Output:

{'Amy Jones': 10, 'Dave Wright': 5, 'Cammy MEele': 4}

Upvotes: 2

Tom
Tom

Reputation: 343

why can you not just store the string respresentation of the dictionary? then use ast to convert it right back?

i.e.

import ast
with open("file.txt", "rb") as f:
     for line in f:
          d = ast.literal_eval(line)

and to write to the file:

with open("file.txt", "wb" ad f:
     f.write(str(d))

this would be fine for relatively small dictionaries, if it was going to store large amounts of players I'd consider using either csv or even a database of some description

Upvotes: 0

timgeb
timgeb

Reputation: 78700

You need to split once from the right. Since your file seems to have unneeded whitespace, I'd do it like this:

with open("Dr Welch.txt") as f:
    d = {}
    for line in f:
        name, score = line.rsplit(None, 1)
        d[name.strip()] = int(score)

I'd also recommend to convert the score to an integer for easier comparison and arithmetic.

Upvotes: 4

Related Questions