tw0fifths
tw0fifths

Reputation: 37

pulling a dictionary out of the function that created it (python)

I am importing a list from an outside document, and inputing that list into a dictionary. This question is applicable to pretty much all values associated to a variable from inside a function. Once the function is complete how do I pull that information from the function with out having to assign the variables as global. Sorry if this question isnt very clear, im having trouble vocalizing it.

Here is the program so far. the dictionary 'result' has values while in the function but when I try to call it from outside the function its empty.

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

Upvotes: 1

Views: 491

Answers (3)

unutbu
unutbu

Reputation: 879729

Use:

result = dictionary(fin)

to assign the value returned by dictionary to the variable result.

Note that result is a global variable, so I'm not sure what you mean by "with out having to assign the variables as global".


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)

Alternatively,

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

Upvotes: 2

wim
wim

Reputation: 362796

Here's a cleaner way, using a generator expression over the dict constructor and using context handlers to manage opening/closing the file handle.

>>> 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!'

Upvotes: 1

Brendan Long
Brendan Long

Reputation: 54242

Assign the result of the function to a variable:

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

Upvotes: 1

Related Questions