如何将csv转换为python中的词典字典?

时间:2016-11-07 13:13:35

标签: python python-3.x csv dictionary anaconda

我有一个CSV文件如下所示。我需要使用python将CSV转换为字典字典。

<div>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>

输出应如下所示

 userId movieId rating
1         16    4
1         24    1.5
2         32    4
2         47    4
2         50    4
3        110    4
3        150    3
3        161    4
3        165    3

请让我知道如何做到这一点。提前致谢

3 个答案:

答案 0 :(得分:2)

您正在寻找嵌套字典。在Python中实现perl的自动修复功能(详细描述见here)。这是一个MWE。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import csv

class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

def main():
    d = AutoVivification()
    filename = 'test.csv'
    with open(filename, 'r') as f:
        reader = csv.reader(f, delimiter=',')
        next(reader)        # skip the header
        for row in reader:
            d[row[0]][row[1]] = row[2]

    print(d)
    #{'1': {'24': '1.5', '16': '4'}, '3': {'150': '3', '110': '4', '165': '3', '161': '4'}, '2': {'32': '4', '50': '4', '47': '4'}}

if __name__ == '__main__':
    main()

test.csv

的内容
userId,movieId,rating
1,16,4
1,24,1.5
2,32,4
2,47,4
2,50,4
3,110,4
3,150,3
3,161,4
3,165,3

答案 1 :(得分:0)

import numpy as np

col1,col2,col3 = np.loadtxt('test2.csv',delimiter=',',skiprows=1,unpack=True,dtype=int)

dataset = {}

for a,b,c in zip(col1,col2,col3):
    if str(a) in dataset:
        dataset[str(a)][str(b)]=str(c)
    else:
        dataset[str(a)]={str(b):str(c)}
print(dataset)

这应该做。上面的示例文件看起来像tsv(制表符分隔值)。如果是这样,请在我的示例中删除分隔符标志。

答案 2 :(得分:0)

import csv
dataset = dict()
with open("file_name", "rb") as csv_file:
    data = csv.DictReader(csv_file)
    for row in data:
        old_data = dataset.get(row["userId"], None)

        if old_data is None:
            dataset["userId"] = {row["movieId"]: row["rating"] }
        else:
            old_data[row["movieId"]] = row["rating"]
            dataset[row["userId"]] = old_data