從csv

2017-04-03 52 views
0

字典裏面字典我對Python非常非常新穎(只編寫了幾個月),而且我很難將自己的頭圍繞在字典中的字典上。從csv

我有一個csv(所以第一行是標題)周圍的期刊和一堆信息的列表,基本上我想要的字典是{期刊名稱:{標題:值}。日記名稱是行中的第二個字符串(在標題之後)。

我只是無法理解我打開csv後如何做到這一點。所有幫助表示讚賞!

f = open('journals.csv') 
csv_f = csv.reader(f) 
rows = [] 
for row in csv_f: 
    rows.append(row) 
    headings = rows[0] #these are the headings from the csv 
    info = rows[1:] #these are the rest of the rows 

dict6 = {} 
dict7 = {} 
for row in info: 
    for i in range(len(row)): 
     dict6[headings[i]] = row[i] 
    dict7[row[0]] = dict6 
'''this is working to be correct except it is matching the wrong journal name to the wrong values(dict6) 

Right now I can't seem to make an if statement to match the list of journal ids to the journal id key in order to match it to the inner dictionary''' 
+1

你有現成的代碼csv文件?如何幾行樣本csv與頭? – tdelaney

+0

事實上,正如@tdelaney所提到的,csv的示例行會有所幫助。 –

+0

我現在添加了一些我的代碼。 – keri112493

回答

0

csv.DictReader將CSV行讀取到字典中。這照顧內在的字典。你可以用一個理解來構建外部字典,這個理解就是把一行中的一個項目作爲關鍵字。

假設

foo,bar,baz 
1,thing1,2 
2,thing2,3 
4,thing3,5 

你可以

>>> import csv 
>>> with open('test.csv', newline='') as fp: 
...  reader = csv.DictReader(fp) 
...  outer_dict = {row['bar']:row for row in reader} 
... 
>>> outer_dict 
{'thing1': {'bar': 'thing1', 'foo': '1', 'baz': '2'}, 'thing3': {'bar': 'thing3', 'foo': '4', 'baz': '5'}, 'thing2': {'bar': 'thing2', 'foo': '2', 'baz': '3'}}