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]]
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:
… 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.