Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating three level nested dictionary in C#

Tags:

c#

dictionary

I want to create a dictionary of the following type,

var data = new Dictionary<string, Dictionary<string, Dictionary<string, int>>>();

when I try to add value to the dictionary in the following way, I get a KeyNotFound Exception.

data[key1][key2][key3]= 3;

What am I doing wrong here? I assume if a key is not found in a dictionary, it is automatically added to it.

otherwise Is there any way to add keys at runtime?

I expect output of following type:

 [male,[animal,[legs,4]

               [eyes,2]]
       [human,[hands,2]
               [ears,2]]

[female,[animal,[nose,1]

                 [eyes,2]]
         [bird,[wings,2]
                 [legs,2]]
like image 951
AnkitG Avatar asked Nov 11 '12 19:11

AnkitG


1 Answers

The problem here is that you are only trying to assign to the innermost dictionary. But the two outer levels does not exist.

You need to be explicit about each level:

if (!data.ContainsKey(key1))
    data[key1]  = new Dictionary<string, Dictionary<string, int>();

... and so on. It can be a bit cumbersome to write, so if you need it a lot, I suggest you create an extension method on dictionary that lets you do this easily.

If you assign to a key in a dictionary, that entry is created. But if you read from a key in a dictionary, and that key does not exist, you get an exception.

like image 61
driis Avatar answered Sep 30 '22 12:09

driis