2017-07-24 114 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