2013-01-17 274 views
4

我想導入CSV到多個詞典在Python蟒蛇導入CSV列表

queryInclude,yahoo,value1 
queryInclude,yahoo,value2 
queryInclude,yahoo,value3 
queryExclude,yahoo,value4 
queryExclude,yahoo,value5 
queryInclude,google,value6 
queryExclude,google,value7 

我理想中的結果將具有行[0] =辭典,行[1] =鍵,行[2] =一個或多個值

queryInclude = { 
     "yahoo": ["value1", "value2", "value3"], 
     "google": ["value6"] } 
queryExclude = { 
     "yahoo": ["value4", "value5"], 
     "google": ["value7"] } 

這裏是我的代碼清單:

import csv 
queryList=[] 
queryDict={} 
with open('dictionary.csv') as csvfile: 
    reader = csv.reader(csvfile, delimiter=',', quotechar='|') 
    for row in reader: 
     queryDict[row[1]] = queryList.append(row[2]) 
     print queryDict 

{'yahoo': None} 
{'yahoo': None} 
{'yahoo': None} 
{'yahoo': None} 
{'yahoo': None} 
{'google': None, 'yahoo': None} 
{'google': None, 'yahoo': None} 

我有靈活性,如果需要改變CSV格式。我上面發佈的理想結果是我已經硬編碼到我的應用程序。我試圖讓它更容易在路上添加更多價值。我花了很多時間研究這個問題,如果我取得更多進展,我會繼續更新。我的思維過程是這樣的...不知道我理解如何構建我的環路,並結合像,同時通過CSV行迭代值有多接近?

for row in reader: 
    where row[0] = queryInclude: 
     create a dictionary combining keys into a list of values 
    where row[0] = queryExclude: 
     create a dictionary combining keys into a list of values 

回答

2

這是幫扶?

import StringIO 
import csv 

csvfile = StringIO.StringIO("""queryInclude,yahoo,value1 
queryInclude,yahoo,value2 
queryInclude,yahoo,value3 
queryExclude,yahoo,value4 
queryExclude,yahoo,value5 
queryInclude,google,value6 
queryExclude,google,value7""") 

reader = csv.reader(csvfile, delimiter=',', quotechar='|') 

dict1={} 
for row in reader: 
    key1, provider, value1 = row 
    if not dict1.has_key(key1): 
     dict1[key1] = {} 
    if not dict1[key1].has_key(provider): 
     dict1[key1][provider] = [] 
    dict1[key1][provider].append(value1) 
+0

這幫助很大。感謝您的幫助! – Jared

3

使用defaultdict防止具有佔所述第一元件加入到字典。它聲明默認的類型時,關鍵是不存在的,必須是創建默認對象可以調用的:

#! python3 
import csv 
from io import StringIO 
from collections import defaultdict 
from pprint import pprint 

data = StringIO('''\ 
queryInclude,yahoo,value1 
queryInclude,yahoo,value2 
queryInclude,yahoo,value3 
queryExclude,yahoo,value4 
queryExclude,yahoo,value5 
queryInclude,google,value6 
queryExclude,google,value7 
''') 

D = defaultdict(lambda: defaultdict(list)) 
for d,k,v in csv.reader(data): 
    D[d][k].append(v) 
pprint(D) 

輸出:

{'queryExclude': {'google': ['value7'], 
        'yahoo': ['value4', 'value5']}, 
'queryInclude': {'google': ['value6'], 
        'yahoo': ['value1', 'value2', 'value3']}} 
+0

這是一個乾淨的實現。 –

+0

謝謝python3的例子。很棒! – Jared