From what I understand, you want to build a dictionary that maps words to lists of words. But that's not what your current code is doing. Instead, your current code is building a dictionary that maps words to words. The problem is on that line:
synonyms[second_word] = first_word
On that line, if there is already an entry for second_word
, then this entry is erased and replaced with first_word
. That means that all previous synonyms are lost, and only the last synonym is kept.
Instead, you should explicitly use lists and .append
. Here are two ways to fix the line synonyms[second_word] = first_word
:
# FIRST WAY
if second_word not in synonyms:
synonyms[second_word] = [first_word] # create new list with one element
else:
synonyms[second_word].append(first_word) # add one element to existing list
# SECOND WAY
synonyms.setdefault(second_word, []).append(first_word) # create new empty list if necessary, and add one element to the list
Finally we get the following code. I chose to use the second way, because it's shorter. But the two ways are equivalent and only a matter of personal taste.
synonyms = {}
while True:
command = input().strip()
if command == "add":
first_word = input().strip()
second_word = input().strip()
synonyms.setdefault(second_word, []).append(first_word)
synonyms.setdefault(first_word, []).append(second_word)
elif command == "count":
word = input().strip()
print(len(synonyms[word]))
Two small notes I'd like to add:
- Instead of using the
.setdefault
method of dict
, there is a third way which is to use collections.defaultdict
instead of dict
. If you're interested, you can read the documentation on defaultdict
, or this stackoverflow question: How does collections.defaultdict work?.
- I added
.strip()
after every call to input()
. This is because the string returned by input()
usually ends with a newline character, which is annoying, since you might end with 'add\n'
instead of 'add'
. String method .strip()
removes all whitespace characters (spaces, tabs and newlines) at the beginning and the end of the string