python将csv转字典,如何在python中将csv转换成字典?_电影观察君的博客-程序员秘密

技术标签: python将csv转字典  

I have a CSV file shown below.I need to convert CSV to dictionary of dictionaries using python.

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

The output should be like shown below

dataset={'1':{'16':4,'24':1.5},

'2':{'32':4,'47':4,'50':4},

'3':{'110':4,'150':3,'161':4,'165':3}}

Please let me know how to do this. Thanks in advance

解决方案

You are looking for nested dictionaries. Implement the perl's autovivification feature in Python (the detailed description is given here). Here is a 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()

The content of 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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_33308507/article/details/118898231

智能推荐

java方法重载和重写_love婧的博客-程序员秘密

java方法重载1.方法的重载是指一个类中可以定义多个方法名相同,但参数不同的方法,调用时,会根据不同的参数自动匹配对应的方法。2.重载的方法,实际上是完全不同的方法,只不过是名称相同而已3.构成方法重载的条件:a.不同的含义:形参类型、形参个数、形参顺序不同b.只有返回值不同不构成方法的重载如:int a(String str) {} 与 void a(String str) {}...

2020-11-30学习记录_Tolonely的博客-程序员秘密

Python学习记录第一次学习python编程学习,感觉挺难的可能是还没有上手。def BMI(name,height,weight): BMI = weight/(height/100)**2 print(("{}的BMI是:{}".format(name,BMI)))BMI("胡凌飞",183,157)C:\Users\86158\AppData\Local\Programs\Python\Python39\python.exe ...

1.3-知识图谱怎么去做?_小磊哥er的博客-程序员秘密

知识图谱怎么去做,这当然不是几句话说得清楚的。首先肯定要先基于自身的业务进行思考,这里整理一些知识图谱构建的主要路径。构建的逻辑思路1、梳理业务,构建本体:是否需要用知识图谱?成本怎么样,能达到怎么的效果?是否有能力构建知识图谱?数据、团队等情况是否能支撑?如果有必要,如何根据业务梳理一套本体框架?2、编辑本体,给出业务知识表示框架:可以利用Protege进行本体编辑,获得一个用OW...

机器学习算法目录_miya_116的博客-程序员秘密

梯度提升决策树GBDT  主成分分析法PCA   偏最小二乘法   kmeans聚类算法原理及其实现逻辑回归——logistics regression(对数几率回归)感知机模型SVM算法原理及其实现...

随便推点

Intent+Bundle 传值_bundle赋值给intent_为意而来的博客-程序员秘密

传值页面:package com.xie.app;import android.app.Activity;import android.content.Intent;import android.os.Bundle;/** * 传值页面 * * @author Hao * */public class MainActivity extends

spring异常记录-----java.lang.NoClassDefFoundError: org/apache/commons/lang3/StringUtils_weixin_34395205的博客-程序员秘密

今天在练习怎样SSH中进行单元測试的时候出现下列异常:SEVERE: Exception starting filter Struts2java.lang.NoClassDefFoundError: org/apache/commons/lang3/StringUtils at com.opensymphony.xwork2.config.providers.XmlConf...

wireshark抓包工具的使用及分析_嵌入式Linux,的博客-程序员秘密

前段时间看到群里在讨论Wireshark抓包工具,想写一篇使用笔记但一直没来得及写,本篇就通过实例来分享wireshark抓包工具的使用。Wireshark简介 Wireshark 是一个...

win10关闭自动更新(权限不够/拒绝访问) 永久 多一个步骤_关闭了自动更新打开没有权限_tqn_qinnan的博客-程序员秘密

一般win10禁止自动更新需要按下win+r打开services.msc  找到windows update,右键属性,启动类型改为禁用 在1803版本中又增加了windows update medic service,这个就相当于windows update的保镖,哪怕你把windows update禁用了,还是会启动更新,所以需要一块禁用了,直接右键属性禁用,会提示拒绝访问,这是由于权...

c的二维数组_c的两元数组_苏言寒的博客-程序员秘密

#include <stdio.h>int main15(){int a[5][10];//1,数组名是常量,不能修改//a=10;//err //2,sizeof(数组名),测数组的总大小5*int[10]=5*4*10=200printf("sizeof(a)=%lu\n", sizeof(a));//3,sizeof(a[0]),测的是第0个元素的大小:int...

推荐文章

热门文章

相关标签