+ 1

Dictionary question

If I write: " if verb_word in verb_dict: verb = verb_dict[verb_word] " 1)Program will try to find this word in dictionary, but where: in keys or in words after keys and ":"? 2)"[verb_word]" is an index or key, or what? I only know that "verb_dict[verb_word]" is word after key. Thanks in advance!

18th Aug 2018, 5:30 PM
Ilyich
4 ответов
+ 7
Dictionaries store key:value pairs. When you did "if verb_word in verb_dict:", 'verb_word' is assumed to be a key, and it searches for that key in the dictionary. If the key was found, the statement "verb = verb_dict[verb_word]" is storing the value associated with the 'verb_word' key in the 'verb' variable. Generally speaking, values are accessed via the keys when dealing with dictionaries. 😁👍🏻
18th Aug 2018, 5:37 PM
Eduardo Petry
Eduardo Petry - avatar
+ 1
1) if verb_word in verb_dict will check the keys 2) [verb_word] is getting the value associated with the key (whatever verb_word is)
18th Aug 2018, 5:42 PM
TurtleShell
TurtleShell - avatar
+ 1
Imagine you were a dictionary. If I asked: Do you know what 'moon' means? ('moon' in dictionary'), you'd answer 'Yes!' (True) If I asked: 'And what does moon mean?' (dictionary['moon']) You'd answer: 'It means...' (Whatever it means/whatever is stored in the dictionary.) ;-)
18th Aug 2018, 5:55 PM
HonFu
HonFu - avatar
+ 1
dictionaries = {key: value} You can separate the keys into a list and separate the values into a list. Then grab the index of the word and pass it as a variable into the other list. Something like below: ''' verb_word=input() verb_dict={ 'run':'cardio', 'sleep':'rest', 'key':'value' } keys=list(verb_dict.keys()) values=list(verb_dict.values()) if verb_word in keys: x = keys.index(verb_word) print(values[x]) elif verb_word in values: x = values.index(verb_word) print(keys[x]) else: print('Word not found') ''' verb_dict[verb_word] = value verb_dict.values() = all values in dict verb_dict.keys() = all keys in dict verb_dict.items() = all key:value pairs Returning a value from a given key is pretty straight forward. However returning a key from a given value requires a little more work
18th Aug 2018, 6:52 PM
Steven M
Steven M - avatar