Reading Data Separated By Colon Per Line In Python
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 user
Solution 1:
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] }
Solution 2:
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']}
Post a Comment for "Reading Data Separated By Colon Per Line In Python"