2016-07-26 44 views
-1

所以我有一個csv文件,我必須從中找到按類別分組的所有產品的平均價格。我設法將文件中的所有行放入列表中。 現在,我想這樣的:如何爲字典中的鍵添加值以查找文件中的鍵? Python

FILE_NAME = 'catalog_sample.csv' 
full_catalog = [] 

with open(FILE_NAME, encoding='utf-8') as file: 
    for line in file:    
     one_record = line.split(',') 
     full_catalog.append(one_record) 

category_dict = {} 
prices = [] 

for i in full_catalog: 
    if str(i[-2]) not in category_dict: 
     category_name = str(i[-2]) 
     category_dict[category_name] = float(i[-1]) 
    else: 
     prices.append(float(i[-1])) 

到目前爲止,我得到一本字典從文件鍵的所有類別,但價值是從文件中的關鍵的第一次出現的價格:

'Men': 163.99 
'Women': 543.99 

看來,「其他」不工作,因爲我期待(添加到鍵的值)。有什麼建議麼?謝謝!

+0

您是否嘗試過任何操作? – Julien

+0

一堆東西,但都沒有工作,我決定不分享它們。 – skipper

+0

如何將元素添加到Python列表中,你知道嗎? – elelias

回答

0

我建議您在瀏覽文件時創建您的字典,而不是將它們添加到列表中,並通過它回溯構建字典。

category_dict = {} 
full_catalog = [] 

with open(FILE_NAME, encoding='utf-8') as file: 
    for line in file: 
     item = line.split(',') 
     # Unpack the last 2 items from list 
     category = item[-2].strip() 
     price = float(item[-1]) 

     # Try get the list of prices for the category 
     # If there is no key matching category in dict 
     # Then return an empty list 
     prices = category_dict.get(category, []) 
     # Append the price to the list 
     prices.append(price) 

     # Set the list as the value for the category 
     # If there was no key then a key is created 
     # The value is the list with the new price 
     category_dict[category] = prices 
     full_catalog.append(item) 

編輯:修改爲匹配提供的行格式。 full_catalog已包含在內,如果您仍然需要整個列表

+0

非常感謝! – skipper

相關問題