2017-07-24 103 views
0

我想导入某些列在这个CSV到嵌套的Python字典: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} } 
+0

**忘了提:如果你想忽略的第一线,你可以在文件处理程序首先调用next(..)头是否在第二行,有没有一种特定的方式来选择列使用(有时我想排除列 - 这个前我想排除工作)** – ben

回答

1

我们可以使用DictReadercsv此:

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'。现在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'}} 

编辑

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
+0

我会建议使用'row.pop('ID') '把它从字典中删除。 – yinnonsanders