Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python创建逐列字典_Python_Csv - Fatal编程技术网

使用python创建逐列字典

使用python创建逐列字典,python,csv,Python,Csv,如何使用python从csv生成列式词典 name, lastname, hobby jhon, g, fishing mike, a, boxing tom, v, sking 输出应为: name = {1 : 'jhon', 2:'mike', 3:'tom'} lastname = {1 : 'g', 2:'a', 3:'v'} hobby = {1 : 'fishing', 2:'boxing', 3:'sking'} 使用,您可以非常轻松地获取列表或词典: >>>

如何使用python从csv生成列式词典

name, lastname, hobby
jhon, g, fishing
mike, a, boxing
tom, v, sking
输出应为:

name = {1 : 'jhon', 2:'mike', 3:'tom'}
lastname = {1 : 'g', 2:'a', 3:'v'}
hobby = {1 : 'fishing', 2:'boxing', 3:'sking'}
使用,您可以非常轻松地获取列表或词典:

>>> import pandas as pd
>>> from StringIO import StringIO
>>> csvfile = StringIO('''name, lastname, hobby
... jhon, g, fishing
... mike, a, boxing
... tom, v, sking''')
>>> 
>>> df = pd.read_csv(csvfile)
>>> dict(df['name'])
{0: 'jhon', 1: 'mike', 2: 'tom'}
>>> list(df['name'])
['jhon', 'mike', 'tom']

这是一个基于矩阵转置的想法

你可以得到元组,但当然你可以在之后转换成列表、集合、dicts或任何东西

_ = raw_input()

m = []

for _ in range(3):
    m.append(raw_input().split(', '))
name, lastname, hobby = zip(*m)

print name
print lastname
print hobby

我会提出以下建议:

# read the csv table
data = [x.strip().split(', ') for x in open('csv').readlines()] 

# transpose the table
data_transposed = map(list, zip(*data)) 
现在检查数据交换行并创建所需的DICT:

for row in data_transposed:
    # the dictionary name is the first element
    name = row[0]
    # the remaining elements are enumerated and put in a dict
    d = dict(enumerate(row[1:]))
    print name, "=", d

为什么要用字典呢?一份清单会更有效率<代码>名称=['jhon','mike','tom']并使用常规索引。@sam同意Martijn Pieters的观点-记录在列表中的位置表示数据中的索引。为什么不创建一个包含所有信息的类
Person
,然后只创建一个列表来存储所有结果,而不是3个列表/dicoWe应尊重OP询问其想法的权利需要。@JanVlcinsky:如果有更好的方法解决这个问题,就不需要了。看起来这里有一个。只需将文件名放到
read\u csv
方法:
df=pd.read\u csv('filename.csv')
如何在这里使用csv文件?数据是在标准输入中读取的,例如在类似unix的操作系统上,我使用这样的脚本
python script.py