dictionary = {}
file = 'lightning.txt'
with open(file) as d:
for line in d:
pa = line.split()
dictionary[pa[0]] = pa[1:]
print(dictionary)
I have a text file that shows lightning players and their goals and assists, it is set up like this:
Stamkos
46
50
Hedman
30
50
Point
40
50
All on separate lines, I am trying to write a program that sends this text file to a dictionary although my output is not displaying how I want it. the dictionary is coming out as {'Stamkos': [], '46': [], '50': [],
I am trying to get rid of the empty lists and just have the name as the key and the goals and assists as the values but nothing is working.
CodePudding user response:
The problem is that the values are in different lines. Use next
to fetch the other ones:
dictionary = {}
file = 'lightning.txt'
with open(file) as d:
for line in d:
dictionary[line.strip()] = [next(d).strip(), next(d).strip()]
print(dictionary)
Output
{'Stamkos': ['46', '50'], 'Hedman': ['30', '50'], 'Point': ['40', '50']}
CodePudding user response:
you can use zip to read 3 lines at a time into 3 separate variables:
players = dict()
with open("lightning.txt","r") as f:
for name,goals,assists in zip(f,f,f):
players[name.strip()] = [int(goals),int(assists)]
print(players)
{'Stamkos': [46, 50], 'Hedman': [30, 50], 'Point': [40, 50]}
Or in a dictionary comprehension:
with open("lightning.txt","r") as f:
players = {name.strip():[*map(int,stats)] for name,*stats in zip(f,f,f)}
Or a (cryptic) mapping of zips:
with open("lightning.txt","r") as f:
players = dict(zip(map(str.strip,f),zip(*[map(int,f)]*2)))
You could also structure your data as nested dictionaries:
players = dict()
with open("lightning.txt","r") as f:
for name,goals,assists in zip(f,f,f):
players[name.strip()] = {"goals":int(goals),"assists":int(assists)}
print(players)
{'Stamkos': {'goals': 46, 'assists': 50},
'Hedman': {'goals': 30, 'assists': 50},
'Point': {'goals': 40, 'assists': 50}}
CodePudding user response:
Another way that also converts the numbers to ints:
file = 'lightning.txt'
with open(file) as d:
names = map(str.strip, d)
ints = map(int, d)
dictionary = {name: [next(ints), next(ints)]
for name in names}
Result (Try it online!):
{'Stamkos': [46, 50], 'Hedman': [30, 50], 'Point': [40, 50]}