2015-12-27 52 views
0

我是新來的,我也是編程新手。我試圖學習自己一點python,我遇到了問題。我有一個非常具體的CSV文件看起來像這樣(我是能夠做到這一點,使用建議這裏Creating a dictionary from a csv file? simplier CSV文件,但現在我掙扎):從特定的csv文件創建字典

1 row: Names,0,1900,1901, ---- ,2015 

2 row: Aaron,0,0,0, ----, 44 

x row: Randomname,0,number_of_babies_named_by_Randomname_in_year_1900, number_of_babies_named_by_Randomname_in_year_1901 

有3550行

總數

有沒有什麼辦法可以創建一個字典我可以導航,所以我可以寫一個函數來告訴我哪一年是最受歡迎的特定名稱,或哪個是最常用的名稱1900年和2015年?

在此先感謝! (抱歉潛在的語法錯誤)

+0

什麼是當您嘗試使用鏈接的問題找到建議你遇到了問題? – ppperry

回答

0

我沒有測試代碼,因爲我沒有csv文件,但我會這樣做。請記住,這是一種快速和骯髒的方式來做到這一點,但我認爲它的工作原理,然後你可以改進它。

import csv 
name_to_year_count = dict() 
f = open('names.csv') 
csv_f = csv.reader(f) 
for row in csv_f: 
    start_year = 1899 
    name = row[0] 
    name_to_year_count[name] = dict() 
    for index, count in enumerate(row, start=1): 
     year = start_year + index 
     name_to_year_count[name][year] = count 

然後找到當年當一個名字是最流行的一種簡單的方法是按密鑰字典的每個名稱:

import operator 

def find_top_year(name): 
    global name_to_year_count 
    name_dict = name_to_year_count[name] 
    # sort in ascending order 
    sorted_year = sorted(name_dict.items(), key=operator.itemgetter(1)) 
    return sorted_year[-1][0] 

你能和你的csv文件測試它?

0

只是爲了讓你從這裏開始是一個想法。
以這樣的方式創建一本詞典,即每一行都是一個條目。
使用名稱作爲字典的關鍵字,而行的其餘部分是您的值。您可以將該值存儲爲列表。因此,例如:

d = {} 
d['Aaron'] = [0,0,0, ----, 44] 

現在你可以很容易地找到在哪一年的名字是最常見的:

year, freq = max(enumerate(d['specific-name']), key = lambda x : x[1]) 
year+1900 

以類似的方式,你可以通過去在發現1900年至2015年間最常見的名字詞典。

0

我想這是大多數你所要求的:

# CSV string (could be read in from a file) 
csvString = """Joseph, 0, 1900, 1901, ---- , 2015 
      Ishmael, 0, 1902, 1904, ---- , 2015 
      Mary, 0, 1904, 1905, ---- , 2015""" 

# Create an empty list to store all the dictionaries 
dictionaryList = [] 

# Split the CSV string into individual CSV lines 
csvList = csvString.split("\n") 

# Loop through all entries in the CSV file 
for csvLine in csvList: 
    # Split CSV string 
    csvValues = csvLine.split(",") 


    # Create dictionary 
    dictionary = {} 
    dictionary["name"] = csvValues[0].strip() 
    dictionary["numberOfBabies"] = csvValues[1].strip() 
    dictionary["year1"] = csvValues[2].strip() 
    dictionary["year2"] = csvValues[3].strip() 

    # Add dictionary to list 
    dictionaryList.append(dictionary) 


# Print contents of all dictionaries  
for dictionaryEntry in dictionaryList:  
    print(dictionaryEntry["name"]) 
    print(dictionaryEntry["numberOfBabies"]) 
    print(dictionaryEntry["year1"]) 
    print(dictionaryEntry["year2"])