Python 2.7 CSV到嵌套Python Dict

Python 2.7 CSV到嵌套Python Dict,python-2.7,csv,dictionary,nested,Python 2.7,Csv,Dictionary,Nested,我想将此csv中的某些列导入嵌套的python目录: 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},

我想将此csv中的某些列导入嵌套的python目录:

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

我们可以使用
csv
中的
DictReader
进行以下操作:

from csv import DictReader

with open('data.csv') as csvfile:
    reader = DictReader(csvfile)
    result = {row[' ID'] : row for row in reader}
现在,
result
将是一个将
ID
s映射到词典的词典。字典还将包含
'ID'
。现在,
结果将是:

{' 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
从csv导入读取器
将open('data.csv')作为csvfile:
下一个(csvfile)
读卡器=听写器(csvfile)
结果={}
对于读取器中的行:
行={k.strip():k的v.strip(),行中的v.items()}

result[row.pop('ID')]=row
我建议使用
row.pop('ID')
将其从字典中删除。忘记提及:标题位于第二行&是否有特定的方法选择要使用的列(有时我想排除列-此示例我想排除作业)