Python: How to pass key to a dictionary from the variable of a function?
dict.update(word=definition)
won’t do what you think it does. See this example:
>>> someDict = {}
>>> word = 'foo'
>>> definition = 'bar'
>>> someDict.update(word=definition)
>>> someDict
{'word': 'bar'}
As you can see, this method will always update the key word
although you want the word
variable to be resolved first. This won’t work though because you are passing a named argument to the update
function, and those named arguments are taken literally.
If you want to update the key that equals to the value of word
, you can just do it like this:
someDict[word] = definition
Dider
Updated on June 14, 2022Comments
-
Dider almost 2 years
Basically I have two dictionaries: one is a
Counter()
the other isdict()
The first one contains all the unique words in a text, as keys and each words' frequency in the text, as the values
The second contains the same unique words as keys, but the values are the definitions which are user-inputted.
The latter is what I'm having trouble implementing. I created a function which takes in a word, checks if that word is in the frequency dictionary, and if it is, allows the user to input a definition of that word (else, it will print an error). The word and its definition are then added to the second dictionary as a key-value pair (using
dict.update(word=definition)
).But whenever I run the program I get the error:
Nameerror: name '' is not defined
Here is the code:
import string import collections import pickle freq_dict = collections.Counter() dfn_dict = dict() def cleanedup(fh): for line in fh: word = '' for character in line: if character in string.ascii_letters: word += character else: yield word word = '' def process_book(textname): with open (textname) as doc: freq_dict.update(cleanedup(doc)) global span_freq_dict span_freq_dict = pickle.dumps(freq_dict) def show_Nth_word(N): global span_freq_dict l = pickle.loads(span_freq_dict) return l.most_common()[N] def show_N_freq_words(N): global span_freq_dict l = pickle.loads(span_freq_dict) return l.most_common(N) def define_word(word): if word in freq_dict: definition = eval(input('Please define ' + str(word) + ':')) dfn_dict({word: definition}) else: return print('Word not in dictionary!') process_book('DQ.txt') process_book('HV.txt') # This was to see if the if/else was working define_word('asdfs') #This is the actual word I want to add define_word('de') print(dfn_dict.items())
I get the feeling that either the error is very small or very big. Any help would be greatly appreciated.
EDIT: So the program now allows me to enter a definition, but returns this error once I do so:
>>> Word not in dictionary! Please define esperar:To await Traceback (most recent call last): File "C:\Users\User 3.1\Desktop\Code Projects\dict.py", line 50, in <module> define_word('esperar') File "C:\Users\User 3.1\Desktop\Code Projects\dict.py", line 37, in define_word definition = eval(input('Please define ' + str(word) + ':')) File "<string>", line 1 To await ^ SyntaxError: unexpected EOF while parsing >>>
-
Dider over 9 yearsThanks, but unfortunately, upon updating the code to use this method I get either a Syntax error (on the "=" symbol). Or (if I delete "return" and just leave it as dfn_dict[word]=definition) a Nameerror again (same as before)
-
poke over 9 yearsYes, you can’t do
return dfn_dict[word] = definition
. You would have to split that into two lines, e.g.dfn_dict[word] = definition
and thenreturn dfn_dict
. But since you are modifying the globaldfn_dict
anyway (btw. no need to call global here), you don’t actually need to return it. -
Dider over 9 yearsNope, still getting the same NameError
-
Riccardo over 9 years@ShihabDider i execute this code and it works, are you sure you replaced input to raw_input? or also to eval(input(..))?
-
Dider over 9 yearsI was mistaken earlier, its not the same NameError, it now says: Name 'raw_input' is not defined. Also I've edited the OP with updated code
-
Dider over 9 yearsEDIT: I tried using eval(input()) the NameError is gone, but now in its place is: SyntaxError unxpected EOF while parsing (see OP for full details)
-
poke over 9 years@ShihabDider
eval(input('Please define ' + str(word) + ':'))
You definitely want to drop theeval
there. -
Riccardo over 9 years@ShihabDider which version of Python are you using?
-
Dider over 9 yearsHaving done this, I now get
dfn_dict({word: definition}) TypeError: 'dict' object is not callable
-
Dider over 9 yearsI'm using Python 3.4.1
-
poke over 9 years@ShihabDider Please read the answer again? You are trying something completely different now.
-
Dider over 9 yearsThanks so much! You were totally right, I changed the key update part, back to your suggestion and it now works perfectly. I just realized I forgot the
.update
attribute.