views:

343

answers:

1

is there a commonly used data structure for mult-key data? e.g. (key1, key2, ..., keyN) -> value. I used to use dictionaries of dictionaries (in c#), and then wrote my own wrapper on top of this to make the syntax look a bit nicer. but it seems like I still have to write a wrapper for each N-dictionary, where N is the number of keys, since I have to define the nested dictionary structure within the code.

assuming I'm using c#, is there a data structure that better encapsulates this sort of usage, and could contain an arbitrary number of keys with hashtable-like lookup performance? I can't simply combine all the keys into a single unique key, because I need to be able to do something like

foreach key2 in data[key1]
    foreach key3 in data[key1][key2]
        foreach key4 in data[key1][key2][key3]
+2  A: 

No, it isn't.

Without breaking type-safety, I think there are two solutions.

  • Dictionaries of Dictionaries - Dictionary<T1, Dictionary<T2, TRes>>
  • Dictionaries of tuples - Dictionary<Tuple3<T1, T2, T3>, Res>. Note that - unlike F# where you could write Map<T1 * T2 * T3, Res> - C# doesn't have a builtin tuple type - you'd have to implement this separately as a generic class or struct.

But regarding your example code, jagged dictionaries (Dictionaries of Dictionaries) are the only alternative.

Dario
your first suggestion seems to be vastly superior to the first to in most cases. It is an approach I find myself using alot. I can't see the benefit of 3 keys if you're just going to use a tuple. Other than that good suggestions.
faceless1_14