Python - Loading File - Dictionary
i'm trying to write a function that will turn my text file into a dictionary with subsets. The text document that i have loaded so far is displayed as showed: 101 102 103 201, John
Solution 1:
import re
classGuest(object):
...
data = []
withopen('data.txt') as f:
for line in f:
tok = re.split(r'\s*,\s*', line.strip())
iflen(tok) > 1:
guest = Guest(tok[1], tok[2], tok[3])
else:
guest = None
data.append((tok[0], guest))
print(data)
Implementing the Guest
class is left as an exercise for the reader.
Solution 2:
I'm not sure if you need the re
module
try this
defload_file( filename ):
text = open( "data.txt" ).readlines()
rooms = {}
for line in text:
room_data = line.strip( '\n' ).split( ',' )
iflen( room_data ) > 1:
#rooms[room_data[0]] = room_data[1:]
rooms[room_data[0]] = tuple( room_data[1:] )
else:
rooms[room_data[0]] = Nonereturn rooms
you mention dictionary in your title but your expected outcome is nested lists.
Edit
Answered?
Post a Comment for "Python - Loading File - Dictionary"