tags:

views:

1240

answers:

3

Hello :)

Just as in title. I would like to use dict as a key in another dict. Something similar to python. I tried this but it gives me errors.

Dictionary<Dictionary<string, string>, int> dict = new Dictionary<Dictionary<string,    string>, int>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
dict2["abc"] = "def";
dict[dict["abc"] = 20;
+4  A: 

It's because the "dict["abc"] is not dictionary, but "string".

The correct, what you asked is:

Dictionary<Dictionary<string, string>, int> dict = new Dictionary<Dictionary<string,    string>, int>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
dict2["abc"] = "def";
dict[dict2] = 20;

But i'm not sure, this is what you realy want/need.

TcKs
I was just typing the same myself.. +1 :)
Steven Robbins
Ok, but how do I get specific key, value pair from inner dict.I don't want to create inner dict for every value in outer dict.
kamilo
dict[dict2["abc"]] = 20 makes more sense to me
Will
+6  A: 

What error is it giving you? Is it complaining about your missing bracket on line 4?

Line 4 looks like it should be:

dict[dict["abc"]] = 20;

However, you probably mean this, since "abc" is not a key of dict:

dict[dict2["abc"]] = 20;

But dict2["abc"] is a string, when the key of dict is supposed to be a Dictionary<string, string>.

But let's re-examine your original goal at this point before going to far down this path. You shouldn't be using mutable types as dictionary keys in the first place.

This may be the code you're looking for:

Dictionary<string, string> dict  = new Dictionary<string, string>();
Dictionary<string, string> dict2 = new Dictionary<string, string>();
dict2["abc"] = "def";
dict[dict2["abc"]] = 20;

But it's hard to tell for sure.

recursive
+3  A: 

Just to throw this in there, I often find that dealing with complicated dictionaries like you describe it's far better to use real names with them rather than trying to let the reader of the code sort it out.

You can do this one of two ways depending on personal preference. Either with a using statement to create a complier alias. Note you have to use the fully qualified type name since this is a compiler alias.

using ComplexKey = System.Collections.Generic.Dictionary<String, String>;
using ComplexType = System.Collections.Generic.Dictionary<
   System.Collections.Generic.Dictionary<String, String>,
   String
   >;

Or you can go the full blown type way and actually create a class that inherits from Dictionary.

class ComplexKey : Dictionary<String, String> { ... }
class ComplexType : Dictionary<ComplexKey, String> { ... }

Doing this will make it far easier for both you and the reader of your code to figure out what you're doing. My general rule of thumb is if I'm creating a generic of a generic it's time to look at building some first class citizens to represent my logic rather.

Peter Oehlert
I will try this solution. Thanks!
kamilo