2016-12-19 60 views
0

我想通過在excel中使用csv文件創建一個字典,該函數通過使用每列的標題在每列中返回一個字典,在我的代碼中口述爲col_list。我有麻煩監守所提供的excel文件,它只返回的標題,「快樂的」和「悲傷」,作爲一本字典,而不是列的內容,就像這樣:在Excel中使用csv在Python中爲每列返回字典

read('words.csv','sad') 
{'a': [], 'd': [], 's': []} 

這裏是鏈接查看該文件:https://docs.google.com/spreadsheets/d/1_qJCvTQfAbk8Df4FrM4vy7GF71v6-dixGiBqx99kmps/edit?usp=sharing

我的代碼:

import csv 
def read(filename, col_list): 
'''This function expects the name of a CSV file and a list of strings 
representing a subset of the headers of the columns in the file, and 
returns a dictionary of the data in those columns''' 

    with open('words.csv', 'r') as f: 
     reader= csv.DictReader(f) 
     dict1={} 
     for col in col_list: 
      dict1[col]=[] 
     for row in reader: 
      return dict1 

(PS您可能需要下載FIE一個CSV才能使用它。)

+1

您遇到的第一個問題是您在使用字符串的地方想要一個字符串列表(''sad''而不是'['sad']')。你的'read'函數還有其他問題,但這是第一個。接下來要考慮的是,如果你在循環中調用return,它仍然只運行一次(因爲它在第一次通過循環時從函數返回)。在Python中,您可能想使用'yield',但是您可能還想調查列表對象的附加方法。 – cco

+0

(a?)問題出現在腳本的最後一行:讀取標題行後立即從函數返回。 – DyZ

+0

你有一本空白名單的字典,因爲這是你放進字典的全部內容。你需要決定你想要它返回什麼,然後弄清楚爲什麼你沒有得到。將這些信息添加到您的問題。 – cco

回答

0

如果我明白你的問題ÿ ou要創建一個字典,即密鑰是文件的標題。並且每個鍵都包含列內容作爲項目。要做到這一點,你的代碼可以是這樣的:

import csv 


def read_csv(filename, col_list): 
    """This function expects the name of a CSV file and a list of strings 
    representing a subset of the headers of the columns in the file, and 
    returns a dictionary of the data in those columns, as described below.""" 

    with open(filename, 'r') as f: 
     # Better covert reader to a list (items represent every row) 
     reader = list(csv.DictReader(f)) 
     dict1 = {} 
     for col in col_list: 
      dict1[col] = [] 
      # Going in every row of the file 
      for row in reader: 
       # Append to the list the row item of this key 
       dict1[col].append(row[col]) 

    return dict1 


print(read_csv(filename='words.csv', col_list=['happy', 'sad'])) 

這段代碼的輸出是:

{'sad': ['abominable', 'abominably', 'abominate', 'abomination', 'abort', 'aborted', 'aborts', 'abrade', 'abrasive', 'abrupt', 'abruptly', 'abscond', 'absence', 'absent-minded', 'absentee', 'absurd', 'absurdity', 'absurdly', 'absurdness', 'abuse', 'abused', 'abuses', 'abusive', 'abysmal', 'abysmally', 'abyss', 'accidental', 'accost', 'accursed', 'accusation', 'accusations', 'accuse', 'accuses', 'accusing', 'accusingly', 'acerbate', 'acerbic', 'acerbically', 'ache', 'ached', 'aches', 'aching', 'acrid', 'acridly', 'acridness', 'acrimonious', 'acrimoniously', 'acrimony', 'adamant', 'adamantly', 'addict', 'addicted', 'addicting', 'addicts', 'admonish', 'admonisher', 'admonishingly', 'admonishment', '', 'OF', 'WELL-BEING', 'ASSURANCE', 'A', 'REASON', 'FOR', 'BEING', 'ACARONAR', 'ACCOMMODATIVE', 'ALTITUDINARIAN', 'AMAZING', 'WORDS', 'AMIABLY', 'ACCOLADE', 'ACUMEN', 'ADJUSTABLE', 'ADMIRER', 'ADMIRING', 'ADMIRINGLY', 'ADORER', 'ADROIT', 'ADROITLY', 'ADULATED', 'ADULATION', 'ADULATORY', 'ADVENTURESOME', 'ADVOCATED', 'AMBITIOUS', 'AMBITIOUSLY', 'AMELIORATE', 'AMENITY', 'AMITY', 'AMPLY', 'AMUSE', 'AMUSINGLY', 'APOTHEOSIS', 'ASSUME', 'YOUR', 'OWN', 'VALUE', 'ASTONISHINGLY', 'ASTONISHMENT', 'ATTRIBUTIONAL', 'STYLE', 'QUESTIONNAIRE', '(ASQ)', 'AUTHENTIC', 'HAPPINESS', 'AWAKEN', 'AWAKENING', ''], 'happy': ['ADORED', 'ADORING', 'ADORINGLY', 'ADVANCED', 'ADVANTAGEOUS', 'ADVANTAGEOUSLY', 'ADVANTAGES', 'AFFABILITY', 'AFFABLY', 'AFFINITY', 'AFFIRMATION', 'AFFIRMATIVE', 'AFFLUENCE', 'AFFLUENT', 'AFFORD', 'AFFORDABLE', 'AFFORDABLY', 'AGILE', 'AGILELY', 'AGREEABLENESS', 'AGREEABLY', 'ALIGNED', 'ALL', 'IS', 'WELL', 'ALLURING', 'ALLURINGLY', 'ALTERNATIVE', 'HEALING', 'ALTRUISTICALLY', 'AMAZE', 'AMAZEMENT', 'AMAZES', 'AMAZINGLY', 'AMIABILITY', 'AMICABILITY', 'AMICABLE', 'AMICABLY', 'AMUSING', 'APPEAL', 'APPEALING', 'APPLAUD', 'APPRECIABLE', 'APPRECIATED', 'APPRECIATES', 'APPRECIATION', 'OF', 'BEAUTY', 'APPRECIATIVELY', 'APPROPRIATE', 'APPROVAL', 'APPROVE', 'ARDOR', 'ART', 'OF', 'APPRECIATION', 'ART', 'OF', 'STILLNESS', 'ART', 'OF', 'WELL-BEING', 'ASSURANCE', 'A', 'REASON', 'FOR', 'BEING', 'ACARONAR', 'ACCOMMODATIVE', 'ALTITUDINARIAN', 'AMAZING', 'WORDS', 'AMIABLY', 'ACCOLADE', 'ACUMEN', 'ADJUSTABLE', 'ADMIRER', 'ADMIRING', 'ADMIRINGLY', 'ADORER', 'ADROIT', 'ADROITLY', 'ADULATED', 'ADULATION', 'ADULATORY', 'ADVENTURESOME', 'ADVOCATED', 'AMBITIOUS', 'AMBITIOUSLY', 'AMELIORATE', 'AMENITY', 'AMITY', 'AMPLY', 'AMUSE', 'AMUSINGLY', 'APOTHEOSIS', 'ASSUME', 'YOUR', 'OWN', 'VALUE', 'ASTONISHINGLY', 'ASTONISHMENT', 'ATTRIBUTIONAL', 'STYLE', 'QUESTIONNAIRE', '(ASQ)', 'AUTHENTIC', 'HAPPINESS', 'AWAKEN', 'AWAKENING']} 

我希望它能幫助。另外,請看ReadDict文檔。 ;)

+0

@Suzaku檢查文件名是否正確(與傳遞的一樣:'words.csv'),並且如果您將正確的參數傳遞給該函數。我在回答你之前就運行了代碼,這很好。 (我甚至給你想要的輸出哈哈) –

+0

@Suzaku你可以把它標記爲答案嗎? –