2013-11-26 70 views
2

因此,我正在編寫一個函數來打開文件,讀取它並將其內容放到字典中。將讀取的文件放在目錄

基本上文件我讀看起來像這樣:

Bread 10 
Butter 6 
Cheese 9 
Candy 11 
Soda 5 

我想確保我的字典裏都會有這種形式:

{ 'bread': 10, 'butter': 6, 'cheese': 9, 'candy': 11, 'soda': 5 } 

那麼,如何才能讓確定這些詞將保持字符串,我會拿出數字作爲int

到目前爲止,這是我如何打開我的文件,但沒有想法如何繼續下去。

def preberi_inventar(dn0501): 
    f = open("dn0501.txt", "r") 
    line = f.readlines() 
    f.close() 
+0

第一步是開始做一些與'line' ......或許你可以'split'呢? – msturdy

+1

我已經得到了答案,無論如何,謝謝:) – Doe

+0

ups,沒有看到那些:) – msturdy

回答

2
d = {} 
with open("dn0501.txt", "r") as f: 
    for line in f: 
     key, val = line.split() 
     d[key] = int(val) 
+2

要得到一個數字作爲要求,你應該使用'd [key] = int(val)'。 – Matthias

+0

@Matthias我的不好。謝謝。更正了帖子。 – Deck

1

我認爲它可以是這樣的:

def preberi_inventar(dn0501): 
    with open("dn0501.txt", "r") as f: 
     return dict([row.split() for row in f])