我想将此csv中的某些列导入嵌套的python dict:
Name, Type, ID, Job, Height
Adam, Man, asmith, factory, 5
Ben, Man, bjones, mine, 6
Jamie, Woman, jbarnes, bank, 5.5
输出:
dict1 = { asmith: {Name:Adam, Type:Man, Height:5},
bjones, {Name:Ben, Type:Man, Height:6},
jbarnes:, {Name:Jamie,Type:Woman, Height:5.5} }
答案 0 :(得分:1)
我们可以使用DictReader
中的csv
:
from csv import DictReader
with open('data.csv') as csvfile:
reader = DictReader(csvfile)
result = {row[' ID'] : row for row in reader}
现在result
将是一个将ID
映射到字典的字典。字典也将包含'ID'
。现在result
将是:
{' bjones': {'Name': 'Ben', ' Type': ' Man', ' Height': ' 6', ' ID': ' bjones', ' Job': ' mine'}, ' jbarnes': {'Name': 'Jamie', ' Type': ' Woman', ' Height': ' 5.5', ' ID': ' jbarnes', ' Job': ' bank'}, ' asmith': {'Name': 'Adam', ' Type': ' Man', ' Height': ' 5', ' ID': ' asmith', ' Job': ' factory'}}
我们可以看到值没有被剥离:这些值包含左侧和右侧的空格。我们可以按如下方式处理这些:
from csv import DictReader
with open('data.csv') as csvfile:
reader = DictReader(csvfile)
result = {}
for row in reader:
row = {k.strip():v.strip() for k,v in row.items()}
result[row.pop('ID')] = row
这也会从词典中删除ID
键。现在答案是:
>>> result
{'jbarnes': {'Name': 'Jamie', 'Height': '5.5', 'Job': 'bank', 'Type': 'Woman'}, 'bjones': {'Name': 'Ben', 'Height': '6', 'Job': 'mine', 'Type': 'Man'}, 'asmith': {'Name': 'Adam', 'Height': '5', 'Job': 'factory', 'Type': 'Man'}}
编辑:如果您想忽略第一行,可以先在文件处理程序上调用next(..)
:
from csv import DictReader
with open('data.csv') as csvfile:
next(csvfile)
reader = DictReader(csvfile)
result = {}
for row in reader:
row = {k.strip():v.strip() for k,v in row.items()}
result[row.pop('ID')] = row