Initialize dictionary inside dictionary C# vs Python

Question:

Why dictionary inside dictionary needs to be explicit in c# e.g. see the following code d1,d2 are fine but on d3 compiler throwing a fit.

var d1 = new Dictionary<string, string> { { "1", "1" } }; //works
var d2 = new Dictionary<string, Dictionary<string, string>> { { "1", d1 } }; //works
var d3 = new Dictionary<string, Dictionary<string, string>> { { "1", { { "1", "1" } } }} //does not work

Python does same and much simpler way

d1:dict={'1':1}
d2:dict = {'1':{'1':1}}
Asked By: Surjit Samra

||

Answers:

You’ve left out the new Dictionary<string, string> part (and one closing }):

var d3 = new Dictionary<string, Dictionary<string, string>> { { "1", new Dictionary<string, string> { { "1", "1" } } } };
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−^

You need to tell C# what concrete instance to create because you could be using a Dictionary subclass:

class SomeDictionarySubclass<K, V> : Dictionary<K, V> {
    // ...
}
// ...
var d3 = new Dictionary<string, Dictionary<string, string>> {
    { "1", new SomeDictionarySubclass<string, string> { { "1", "1" } } }
};
Answered By: T.J. Crowder
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.