- Home /
How am I accessing my Dictionary wrong?
So I have been racking my brain on this for a couple of days now and I can't figure it out. It has to be something simple that I'm doing wrong. So in the code below I have a dictionary set up for a prototype of a word game I'm making. It's very simple just both the key and values are a string of the word itself. However no matter what I do the only key that returns true when I look through the dictionary is the very last word in my TextAsset no matter the size or whether or not I use and ordered Dictionary or a regular dictionary. I've gone through a million options but can't figure out how to be able to query my dictionary correctly.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System.Collections.Specialized;
public class DictionaryTest : MonoBehaviour {
//Dictionary<string, string> myDictionary = new Dictionary<string, string>();
//HashSet<string> myOtherDictionary = new HashSet<string>();
public string wordToCheck;
TextAsset myTextAsset;
//char[] delimeters = { '\r', '\n' };
List<string> myList = new List<string>();
//int counter = 0;
//string myValue;
OrderedDictionary myOrderedDictionary = new OrderedDictionary();
ICollection keyCollection;
ICollection valueCollection;
int dictionarySize;
private void Awake()
{
myTextAsset = Resources.Load("DictionaryTest", typeof(TextAsset)) as TextAsset;
foreach (string word in myTextAsset.text.Split('\n'))
{
myList.Add(word);
}
}
// Use this for initialization
void Start () {
foreach (string word in myList)
{
myOrderedDictionary.Add(word, word);
}
//foreach (string word in myTextAsset.text.Split('\n'))
//{
// myOtherDictionary.Add(word);
//}
//myDictionary.Clear();
//myDictionary = myTextAsset.text.Split('\n').ToDictionary(w => w);
Debug.Log("There are " + myOrderedDictionary.Count + " items in myOrderedDictionary.");
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButtonDown(0))
{
//if (CheckWord(wordToCheck))
//{
// Debug.Log(wordToCheck + " is a valid word");
//}
//else if(!CheckWord(wordToCheck))
//{
// Debug.Log(wordToCheck + " is NOT a valid word");
//}
//if (myDictionary.TryGetValue(wordToCheck, out myValue))
// {
// print(myValue + " exixts");
//}
//if (myOtherDictionary.Contains(wordToCheck))
//{
// print(wordToCheck + "exists in myOtherDictionary");
//}
keyCollection = myOrderedDictionary.Keys;
valueCollection = myOrderedDictionary.Values;
dictionarySize = myOrderedDictionary.Count;
PrintContents();
if (myOrderedDictionary.Contains(wordToCheck))
{
print(wordToCheck + " exists in myOrderedDictionary");
}else if
(!myOrderedDictionary.Contains(wordToCheck))
{
print(wordToCheck + " does NOT exist in myOrderedDicionary");
}
}
}
public void PrintContents()
{
string[] myKeys = new string[dictionarySize];
string[] myValues = new string[dictionarySize];
keyCollection.CopyTo(myKeys, 0);
valueCollection.CopyTo(myValues, 0);
for (int i = 0; i < dictionarySize; i++)
{
print("Key: " + myKeys[i] + " Value: " + myValues[i]);
}
}
//public bool CheckWord(string word)
//{
// return myDictionary.ContainsKey(word);
//}
}
As you can see I've been doing a lot of testing so forgive me, and it's also just prototyping code so I haven't been keeping things nice looking or cared about structure.
The last thing I attempted was an Ordered Dictionary using a sorted list and parsing my text asset simply by the '\n' delimeter, and then feeding that into my dictionary. However the outcome was still the same no matter how I created the dictionary.
As you can see the word aalii is showing as nonexistent in my dictionary but it is clearly represented in the list there, whereas aals does exist as the final key/value pair and queries true.
I've checked the text document just in case and it is set up just fine, no extra spaces or unforseen errors in it. I am using Visual Studios to create the text documents but I don't know why that matters. I'm also using Unity 5.6.1f1.
Answer by tanoshimi · Aug 23, 2017 at 08:32 PM
The fact that the last value is always the only one that is being tested correctly, no matter what that value is, suggests that there's a problem with the delimiter in your text asset between all the other entries.
You're splitting your text file based on the "\n" delimiter - are you sure that the separator is not "\r\n", for example? (in which case, the entry which you believe to be "aalii" is actually "aalii\r", although would be displayed exactly the same in the console log).
Well I've tried a few more things and it's still not acting correctly. I even went as far as Trim$$anonymous$$g both the front and back of each string of blank space as well as '\r' before populating my dictionary but it still only returns true on the final entry. I'm still splitting the words with '\n'.
So it turns out you were right but I still came across something weird while I was attempting to trim my text. if I looped through the text list and trimmed the words before I added them to the dictionary it didn't work properly. However when I trimmed the words as I added them to the dictionary it worked just fine.
Code that didn't work:
foreach (string word in myList)
{
word.Trim();
myOrderedDictionary.Add(word, word);
}
Code that did work:
foreach (string word in myList)
{
myOrderedDictionary.Add(word.Trim(), word.Trim());
}
strings are immutable objects. This line:
word.Trim()
is completely pointless. Trim returns the trimmed string and you don't do anything with it. You have to do:
word = word.Trim();
Why don't you trim the word before you add it to your list in line 29?
Your answer
![](https://koobas.hobune.stream/wayback/20220612133407im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
ReadLine to a Variable 2 Answers
Optimising dictionary load (in Javascript) 2 Answers
Parse Json Response through Dictionary object 1 Answer
Split Textasset into List 1 Answer
How can i split a string[] ? 1 Answer