字典作为另一个字典中一个键的值

时间:2017-07-22 10:21:42

标签: c# dictionary

我不知道如何将包含多个项目的字典添加到另一个字典作为值

Dictionary<string,Dictionary<string,double>> proptest=new Dictionary<string,Dictionary<string,double>>
if (proptest.ContainsKey(filenametest))
                {

                    proptest[filenametest].Add(filenametraining, NB) ;
                }
                else
                {
                    proptest.Add(filenametest, new Dictionary<string, double> { { filenametraining, NB } });
                }

结果是: {[10171.txt,System.Collections.Generic.Dictionary`2 [System.String,System.Double]]} 虽然我想要的结果是: {[10171.txt:(cat10 0.4)(cat3 0.6)]}

1 个答案:

答案 0 :(得分:0)

您可以添加如下现有词典:

// The 'outer' dictionary:
var myDictionary = new Dictionary<string, Dictionary<string, double>>();

// an existing 'inner' dictionary:
var innerDictionary1 = new Dictionary<string, double> { 
    { "inner1.1", 6 }, { "inner1.2", 4.5 } 
};

// add the inner to the outer:
myDictionary.Add("outer1", innerDictionary1);

要内联添加'内部'字典:

myDictionary.Add("outer2", 
    new Dictionary<string, double> { 
        { "inner2.1", 3.48748}, { "inner2.2", 25 }, { "inner2.3", 0 } 
    });

此外,如果要将值添加到内部字典,可以执行以下操作:

myDictionary["outer2"].Add("inner2.4", 3.56);