问题
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.
回答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']}
回答2:
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] }
来源:https://stackoverflow.com/questions/28385822/reading-data-separated-by-colon-per-line-in-python