Reputation: 303
I'm currently learning about data mining and one of the examples in the ebook I'm reading had a dictionary to store every user and their ratings for a song. This is the initialization of the dictionary that was given.
users ={"Angelica": {"Blues Traveler": 3.5, "Broken Bells": 2.0,
"Norah Jones": 4.5, "Phoenix": 5.0,
"Slightly Stoopid": 1.5,
"The Strokes": 2.5, "Vampire Weekend": 2.0},
"Bill": {"Blues Traveler": 2.0, "Broken Bells": 3.5,
"Deadmau5": 4.0, "Phoenix": 2.0,
"Slightly Stoopid": 3.5, "Vampire Weekend": 3.0},
"Chan": {"Blues Traveler": 5.0, "Broken Bells": 1.0,
"Deadmau5": 1.0, "Norah Jones": 3.0,
"Phoenix": 5, "Slightly Stoopid": 1.0}}
I'm stuck on figuring out how to create this same dictionary if the same values were in a text file where each line contains the information of each user. This would be an example of the first line in the text file:
Angelica, "Blues Traveler": 3.5, "Broken Bells": 2.0, "Norah Jones": 4.5, "Phoenix": 5.0, "Slightly Stoopid": 1.5, "The Strokes": 2.5, "Vampire Weekend": 2.0
What I have so far:
with open(text_file) as f:
for line in f:
songs = line.split(',')
for current_song in songs
ratings = current_songs.split(':')
I'm not too sure how create the dictionary. The nested dictionaries have been confusing me for a few hours.
Upvotes: 0
Views: 942
Reputation: 9636
Can be made more concise with json library. We will do following:
First lets split the line and separate artists name and data. So, string Angelica, "Blues Traveler": 3.5, "Broken Bells": 2.0, "Norah Jones": 4.5,...
is split into two strings Angelica
and second string "Blues Traveler": 3.5, "Broken Bells": 2.0, "Norah Jones": 4.5,...
username, songs = line.split(',', 1)
If you observe carefully, the second string can be easily converted to a dictionary by importing it into json.loads
, however it does not have {
and }
to make it a valid json. So we will add it manually and import it into json.
songs = "{%s}" % songs
json.loads(songs)
So total code is:
import json
user = {}
with open('my.txt') as f:
for line in f:
username, songs = line.split(',', 1)
songs = "{%s}" % songs
user[username] = json.loads(songs)
print user
Upvotes: 0
Reputation: 249444
users = {}
with open(text_file) as f:
for line in f:
parts = line.rstrip().split(', ')
name = parts[0]
users[name] = {}
for rating in parts[1:]:
song, score = rating.split(': ')
song = song[1:-1]
users[name][song] = score
print users
Upvotes: 4