2012-02-14 67 views
1

我從外部文檔導入列表,並將該列表輸入到字典中。這個問題適用於幾乎所有與函數內部的變量相關的值。一旦函數完成,我該如何從函數中提取信息,而不必將變量賦值爲全局變量。對不起,如果這個問題不是很清楚,我很難發聲。將字典從創建它的函數中拉出來(python)

這是迄今爲止的計劃。字典的'結果'在函數中有值,但是當我試圖從函數外調用它時它是空的。

fin = open('words.txt') 

def dictionary(words): 
    result = {} 
    for line in words: 
     result[line] = 'yupp!' # dont care about value at the moment 
    return result 

word_dict = dictionary(fin) 
'the' in word_dict# checking to see if a word is in the dictionary 

回答

2

用途:

​​3210

分配由dictionary回到變量result值。

請注意result是一個全局變量,所以我不確定你的意思是「用 不必將變量賦值爲全局變量」。


def dictionary(words): 
    result = {} 
    for word in words: 
     word = word.strip() 
     result[word] = 'yupp!' 
    return result 

with open('words.txt') as fin: 
    result = dictionary(fin) 
    print('the' in result) 

或者,

def dictionary(words): 
    return dict.fromkeys((word.strip() for word in words), 'yupp') 
+0

*燈泡*我知道我錯過了一件關鍵的事情。當我查看某個值是否在我的字典中時,我已經做出了您建議的更改,但它完全沒有返回任何結果。不是真或假。 – tw0fifths 2012-02-14 03:00:24

+0

這可能是由於'line'以'\ n'結尾。嘗試'line = line.strip()'。我已經添加了一些代碼來顯示我的意思。 – unutbu 2012-02-14 03:04:30

+0

這就是它。起初,我試圖做'line.strip()'出去分配給任何東西。當我放置你的'line = line.strip()'它奇妙地工作!我需要確定何時需要爲某個值分配某些內容,何時不需要。像'a.strip()'需要分配給某個東西,而'sorted(list)'不需要。 – tw0fifths 2012-02-14 03:26:04

1

分配功能到一個變量的結果:

result = dictionary(fin) # note that this variable does not need to be named 'result' 
1

這裏的一個清潔的方式,使用生成表達在字典構造函數和m使用上下文處理程序Aage打開/關閉文件句柄。

>>> def dictionary(fname='/usr/share/dict/words'): 
... with open(fname) as words: 
...  return dict((word.strip(), 'yupp!') for word in words) 
... 
>>> my_dictionary = dictionary() 
>>> 'the' in my_dictionary 
True 
>>> my_dictionary['the'] 
'yupp!' 
+0

因此,我在檢查密鑰時得到它返回False。無法弄清楚爲什麼一切都是錯誤的。所以我打印了整個字典,每個字都有'\ n'。我需要去掉那個。 – tw0fifths 2012-02-14 03:08:24

+0

呵呵?上面的方法已經剝離換行符。 – wim 2012-02-14 03:09:35

+0

對不起,我感到困惑。你的代碼工作完美!我在錯誤的方框中寫了我的評論。 – tw0fifths 2012-02-14 03:27:38