Convert Nested Dictionary to CSV Table

后端 未结 3 1216
鱼传尺愫
鱼传尺愫 2020-12-19 23:30

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

users = {
    \"Angelica\": {
        \"Blues Traveler\": 3.5, 
        \"         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-20 00:19

    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)
    

提交回复
热议问题