I need to get the count of values for a specific key in dictionary.
len(synonyms[word])
just gives me the length of the word I have added to the dictionary and not the value count for the key.
This is my attempt:
synonyms = {}
while True:
command = input()
if command == "add":
first_word = input()
second_word = input()
synonyms[second_word] = first_word
synonyms[first_word] = second_word
elif command == "count":
word = input()
print(len(synonyms[word]))
Output:
CodePudding user response:
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 ofdict
, there is a third way which is to usecollections.defaultdict
instead ofdict
. If you're interested, you can read the documentation ondefaultdict
, or this stackoverflow question: How does collections.defaultdict work?. - I added
.strip()
after every call toinput()
. This is because the string returned byinput()
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