I need to create a CSV file filled with data from a nested dictionary.
I am referring to this question: Convert Nested Dictionary to CSV Table.
I checked this problem: From Nested Dictionary to CSV File, and found a way to create comma-separated values.
My nested dictionary looks like this:
users_item = {
"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}
}
with open('output1.csv', 'w') as csv_file:
csvwriter = csv.writer(csv_file, delimiter=',')
for session in users_item:
for item in users_item[session]:
csvwriter.writerow([session, item, users_item[session][item]])
I generated this output.
Angelica,Blues Traveler,3.5
Angelica,Broken Bells,2.0
Angelica,Norah Jones,4.5
Angelica,Phoenix,5.0
Angelica,Slightly Stoopid,1.5
Angelica,The Strokes,2.5
Angelica,Vampire Weekend,2.0
Bill,Blues Traveler,2.0
Bill,Broken Bells,3.5
Bill,Deadmau5,4.0
Bill,Phoenix,2.0
Bill,Slightly Stoopid,3.5
Bill,Vampire Weekend,3.0
However, I need to generate the output in the following format:
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
Could you please tell me how to modify the code to obtain the output that I showed above?