- Home /
Can't assign dictionary values
Hello! I have a little problem here. I searched how to do it. But I didn't come with something good. So, I'm trying to assign values in a "complex" dictionary, but I can't seem to do it. The error says : KeyNotFoundException : The key given was not present in the dictionary.
dimensionsCameras = new Dictionary<int, Dictionary<int, float[]>>();
dimensionsCameras[0][0] = new float[] { 0f, 0f, 1f, 1f }; // 1 joueur - joueur 1
dimensionsCameras[1][0] = new float[] { 0f, 0.5f, 0.9f, 0.5f }; // 2 joueurs - joueur 1
dimensionsCameras[1][1] = new float[] { 0.1f, 0f, 0.9f, 0.5f }; // 2 joueurs - joueur 2
This is a dictionary not a jagged array. The purpose of dictionary is the key-value pair. So it means you know the key and want the value. Considering a [i][j] indexing is kinda wrong as you cannot know where the items are stored. I don't even think indexing is possible like this.
Answer by DoTA_KAMIKADzE · May 14, 2015 at 06:32 PM
The error says what it says - you can access (get/set) in that manner only existing keys, firstly you'll need to populate your dictionary, like so:
dimensionsCameras = new Dictionary<int, Dictionary<int, float[]>>();
Dictionary<int, float[]> nestedDict = new Dictionary<int,float[]>();
nestedDict.Add(0, new float[] { 0f, 0f, 1f, 1f });
dimensionsCameras.Add(0, nestedDict);
//next time you'll be able to set or get it like dimensionsCameras[0][0] because Key 0 Key 0 already exists
//you can also use if statements to check if key exists, e.g.:
if (dimensionsCameras.ContainsKey(0)) //might be useful if you're not initializing it all in one go and can add few more
Answers are quick here! And thanks. It worked like a charm altought it's quite a compact code.
Your answer
Follow this Question
Related Questions
Dictionary doesn't exist? 1 Answer
How do I assign the velocity on the "y" axis to a float? 1 Answer
How to get accurate values from curves using Mecanim 0 Answers
How do I create a Key and Values Dictionary array in C# 1 Answer
Assigning a value to a Dictionary key changes other key values 0 Answers