Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# C# Collections Sets and Dictionaries The System.Collections.Generic Namespace

evanpavan
evanpavan
5,025 Points

For the previous code challenge I'm stuck at "Bummer: The given key was not present in the dictionary."

I'm getting the following error from the code challenge Bummer: The given key was not present in the dictionary. I'm not sure what to do here as the error seems wrong. I'm declaring the AddWord method and using the variable word passed in the parameter to find the WordCount int value. The variable word shouldn't be tested against the Dictionary to see if it's a key because it's an undefined variable in the current context, and the Dictionary is null for all I know.

Here's my code. Pretty straight forward. I've added the following to the given AddWord method.

 WordCount[word]++; 

Here's the full code:

using System.Collections.Generic;

namespace Treehouse.CodeChallenges
{
    public class LexicalAnalysis
    {
        public Dictionary<string, int> WordCount = new Dictionary<string, int>();

        public void AddWord(string word)
        {
            WordCount[word]++; 
        }
    }
}
evanpavan
evanpavan
5,025 Points

Here's the solution: What the error must have mean't by key does not exist is that the method we are creating needs to have additional code to handle the scenario when the key passed does not exist in the dictionary

Added an if and TryGetValue

        public void AddWord(string word)
        {
            int value;
            if(WordCount.TryGetValue(word, out value))
            {
                WordCount[word]++;
            }
            else
            {
                WordCount.Add(word, 1);
            }
         }   

1 Answer

public class LexicalAnalysis { public Dictionary<string, int> WordCount = new Dictionary<string, int>();

    public void AddWord(string word)
    {
        if(WordCount.ContainsKey(word))
        {
            WordCount[word] = WordCount[word] + 1;
        }
        else
        {
            WordCount.Add(word, 1);   
        }
    }