将嵌套字典转换为CSV表

时间:2014-07-25 07:04:55

标签: python python-2.7 csv dictionary

我正在进行数据挖掘tutorial,并且我正在使用以下词典。

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
    }
}

我想将其转换为.csv文件,这样当我在Excel中打开它时,我会得到一个表格,其中包含行侧的歌曲和列侧的名称: Table with the ratings as values

是否有任何内置的python方法可以帮助我实现这一目标?

3 个答案:

答案 0 :(得分:2)

您必须从包含行的列转置到包含列的行。使用collections.defaultdict() object最简单:

rows = defaultdict(dict)

for user, artists in users.iteritems():
    for artist, count in artists.iteritems():
        rows[artist][user] = count

现在您的词典可以直接写入csv.DictWriter()

with open(csvfilename, 'wb') as outf:
    writer = csv.DictWriter(outf, [''] + users.keys())
    writer.writeheader()
    writer.writerows(dict(row, **{'': key}) for key, row in rows.iteritems()) 

需要生成器表达式为rows字典中的每个值添加第一列键值对。

演示:

>>> from collections import defaultdict
>>> import csv
>>> users = { ... }  # elided for brevity
>>> rows = defaultdict(dict)
>>> for user, artists in users.iteritems():
...     for artist, count in artists.iteritems():
...         rows[artist][user] = count
... 
>>> import sys
>>> writer = csv.DictWriter(sys.stdout, [''] + users.keys())
>>> writer.writeheader()
,Angelica,Veronica,Sam,Jordyn,Dan,Bill,Chan,Hailey
>>> writer.writerows(dict(row, **{'': key}) for key, row in rows.iteritems()) 
The Strokes,2.5,3.0,5.0,4.0,4.0,,,4.0
Blues Traveler,3.5,3.0,5.0,,3.0,2.0,5.0,
Phoenix,5.0,4.0,5.0,5.0,3.0,2.0,5,
Broken Bells,2.0,,2.0,4.5,4.0,3.5,1.0,4.0
Deadmau5,,,,4.0,4.5,4.0,1.0,1.0
Norah Jones,4.5,5.0,3.0,5.0,,,3.0,4.0
Slightly Stoopid,1.5,2.5,4.0,4.5,4.5,3.5,1.0,
Vampire Weekend,2.0,,,4.0,2.0,3.0,,1.0

答案 1 :(得分:2)

试试这个

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)

答案 2 :(得分:0)

import pandas as pd
data = pd.DataFrame(users)
data = data.fillna("-")
data.to_csv("./users.csv")