0

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:

Axe319
  • 4,255
  • 3
  • 15
  • 31
Muffin
  • 55
  • 1
  • 1
  • 8
  • It's hard to understand what you are doing and what you want to do. Could you please modify your code to make it a [mre]? In particular, avoid using `input()` when posting code on stackoverflow. Instead, include the input as hardcoded data in your post, so that we can see exactly what input you're running your code on. – Stef Nov 30 '21 at 12:15
  • With "count of values", do you mean how many values are attached to a specific key? Because with a dictionary, there will always be one entry per key. – Kroshtan Nov 30 '21 at 12:15
  • @Kroshtan it looks like OP is expecting for multiple assignments to a key to be added as a `list` but without any actual `input` or clarification, it's hard to tell without guessing. – Axe319 Nov 30 '21 at 12:19
  • The input I'm running is in the "output" image. Command "add" -> input "Eriks" -> input "Zilais" -> command "count" -> input the key you wan't to get the values count of "Eriks". So the count command + input of the key "Eriks" should return me "1", because in that key there is only one value. – Muffin Nov 30 '21 at 12:22
  • @Muffin every key will always have one value for a `dict` unless its value is a `list`. See the answer @Stef posted. – Axe319 Nov 30 '21 at 12:24

1 Answers1

1

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
Stef
  • 13,242
  • 2
  • 17
  • 28
  • Oh, right, lol. Sorry that it was that hard to understand what I want to produce here, but you got it all right. Thank you, worked like a charm! :) – Muffin Nov 30 '21 at 12:31
  • @Muffin It wasn't really that hard to understand, because the problem was simple. But using `input()` makes it more annoying to reproduce your issue, so I strongly suggest you try to avoid it the next time you ask a question. You're more likely to receive an answer if it's easy to reproduce your issue. For instance, you could write: `hardcoded_input = iter('add king monarch add queen monarch count king count monarch'.split())` then replace every `input().strip()` with `next(hardcoded_input)`. – Stef Nov 30 '21 at 12:37