-1

I'm creating a program that has the user's name and their answers to a guess the number game in a database - like format on Python. I have created a text file where all of the users' data is, in the form name : guess. For instance,

Dave:23
Adam:12
Jack:13
Dave:25
Adam:34

Now, I am trying to re - read the file into Python as a tuple, so I decided to use the line of code below (The real answer is 17):

dict(line.split(':', 1) for line in open('guesses.txt'))

But this will just hand me back an empty line in the IDLE.
Why is this not working?
To make it more simple, I need a tuple that has the user's name and then their guesses.

My dictionary should look like this:

{'Dave': 23 25, 'Jack' : 13, 'Adam' : 13 34}

Thanks, Delbert.

Delbert J. Nava
  • 121
  • 1
  • 9

2 Answers2

3
from collections import defaultdict

result = defaultdict(list)
with open("guesses.txt") as inf:
    for line in inf:
        name, score = line.split(":", 1)
        result[name].append(int(score))

which gets you

# result
{ "Dave": [23, 25], "Jack": [13], "Adam": [12, 34] }
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
  • 2
    I do not think that your answer is correct. It does not deal with the special fact that "Dave and Adam are separately the same people. Dave is Dave.T and Adam is Adam.G" ;) -- ha, this is fun. – Dr. Jan-Philip Gehrcke Feb 07 '15 at 18:40
1

Use a defaultdict and store values in a list:

s="""Dave:23
Adam:12
Jack:13
Dave:25
Adam:34
"""

from collections import defaultdict
d = defaultdict(list)

for line in s.splitlines():
    name,val = line.split(":")
    d[name].append(int(val))

print(d)
defaultdict(<class 'list'>, {'Jack': [13], 'Adam': [12, 34], 'Dave': [23, 25]})

So for your file just do the same:

d = defaultdict(list)
with open('guesses.txt') as f:
    for line in f:
        name,val = line.split(":")
        d[name].append(int(val))

Your own code should return {'Jack': '13', 'Dave': '25', 'Adam': '34'} where the the values for Dave and Adam are overwritten in the last two lines hence the need to store values in a list and append.

You also cannot use tuples as you mentioned in your answer without creating new tuples each time you want to add a new value as tuples are immutable.

You can print(dict(d)) or use pprint if you don't want the defaultdict(<class 'list'>,)

from pprint import pprint as pp

pp(d)
{'Adam': ['12', '34'],
 'Dave': ['23', '25'],
 'Jack': ['13']}
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321