2017-03-09 67 views
0

的Python 3個沒有捷徑:字典保存到文件/在字典數項

好傢伙我是一個Python初學者學習詞典現在

下面

是我迄今瞭解如何保存列表到文件

和計數列表中的項目如下。

class item: 
    name = None 
    score = None 

def save_list_in_file(file_name:str, L:[item]): 
    f = open(file_name,'w') 
    for it in L: 
     f.write(it.name + "" + str(it.score)) 
    f.close() 

def count_item_in_list(L:[item])->int: 
    n = 0 
    for it in L: 
     if it.score >= 72: 
     n += 1 
    return n 

,我不知道,如果使用字典是相同的方式,我在列表

例如使用:

def save_dict_to_file(file_name:str, D:{item}): 
    f = open(file_name,'w') 
    for it in D: 
     f.write(it.name + "" + str(it.score)) 
    f.close() 

def count_item_in_dict(D:{item})->int: 
    n = 0 
    for it in D: 
     if it.score <= 72: 
     n += 1 
    return n 

將是正確的?我認爲字典與使用列表不同。

感謝您的任何評論!

+0

哎呀沒有捷徑意味着我不能使用簡單的模塊。 – David

回答

0

不能像使用列表一樣使用字典。

列表被定義爲一系列元素。所以,當你有名單:

L=['D','a','v','i','d'] 

您可以循環像這樣:

for it in L: 
     print(it) 

它會打印:

D 
    a 
    v 
    i 
    d 

相反,一本字典是一組元組兩個要素中一個是關鍵,另一個是價值。因此,例如你有一個Dictonary這樣的:

D = {'firstletter' : 'D', 'secondletter': 'a', 'thirdletter' : 'v' } 

當你循環它像一個列表:

for it in L: 
     print(it) 

將只打印鍵:

firstletter 
    secondletter 
    thirdletter 

所以爲了要獲得您必須打印它的值如下:

for it in D: 
     print(D[it]) 

,將顯示這個結果:

D 
a 
v 

如果您需要了解更多信息,你可以去查文檔,字典:)

Python 3 documentation of Data Structures