Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

python - Convert Nested Dictionary to CSV Table

I'm going through a data mining tutorial and I'm using the following dictionary.

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
    },
    "Dan": {
        "Blues Traveler": 3.0, 
        "Broken Bells": 4.0, 
        "Deadmau5": 4.5, 
        "Phoenix": 3.0, 
        "Slightly Stoopid": 4.5, 
        "The Strokes": 4.0, 
        "Vampire Weekend": 2.0
    },
    "Hailey": {
        "Broken Bells": 4.0, 
        "Deadmau5": 1.0, 
        "Norah Jones": 4.0, 
        "The Strokes": 4.0, 
        "Vampire Weekend": 1.0
    },
    "Jordyn":  {
        "Broken Bells": 4.5, 
        "Deadmau5": 4.0, 
        "Norah Jones": 5.0, 
        "Phoenix": 5.0, 
        "Slightly Stoopid": 4.5, 
        "The Strokes": 4.0, 
        "Vampire Weekend": 4.0
    },
    "Sam": {
        "Blues Traveler": 5.0, 
        "Broken Bells": 2.0, 
        "Norah Jones": 3.0, 
        "Phoenix": 5.0, 
        "Slightly Stoopid": 4.0, 
        "The Strokes": 5.0
    },
    "Veronica": {
        "Blues Traveler": 3.0, 
        "Norah Jones": 5.0, 
        "Phoenix": 4.0, 
        "Slightly Stoopid": 2.5, 
        "The Strokes": 3.0
    }
}

I want to convert this into a .csv file so that when I open it in Excel, I get a table with the songs on the rows side and the names on the columns side: Table with the ratings as values

Are there any in-built python methods which will help me achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this

import csv
# Create header line
a = ["Album/Track"] + users.keys()

# Create unique keys.
x = list(set([y for z in users.values() for y in z.keys()]))

# Create rows
rows = [a]+[[q]+[users[p].get(q, '-') for p in a[1:]] for q in x]

with open('my.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile)
    for row in rows:
        writer.write(row)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...