I have a structure that can be very easily represented using a three-deep nested dictionary, like so
private static Dictionary<string, Dictionary<string, Dictionary<string,string>>> PrerenderedTemplates;
Where the structure might be used something like this
PrerenderedTemplates[instanceID][templategroup][templatepart]
Now, I realise that this code is hard to read, because from looking at the definition statement, you can't tell what it's being used for. The only advantage I can really see in changing it to Dictionary<string, PrerenderedTemplate>
is readability. Converting each nesting into its own class (e.g class PrerenderedTemplate{} class TemplateGroup{} class TemplatePart{}
) would add many more lines of code for little (if any) computational advantage. As far as I can see.
Dictionary
works in the documentation/commentsUpdate
So, inspired by Reza, but unable to use Tuples, I decided to create my own key generator and implement his pattern like this:
private Dictionary<string, string> PrerenderedTemplates;
private string GetPrerenderedTemplateKey(string InstanceId, string FeatureId, string OptionId)
{
return new StringBuilder(instanceId)
.Append(FormatTools.LIST_ENTRY_DELIMITER)
.Append(templategroup)
.Append(FormatTools.LIST_ENTRY_DELIMITER)
.Append(templatepart).ToString();
}
Where FormatTools.LIST_ENTRY_DELIMITER
is the Unicode Private Use Character 0xe04d
.
flatdict is a Python library that creates a single level dict from a nested one and is available from Python 3.5 onwards. We've seen so far that writing our custom solution may not be ideal, and using a full-blown library like pandas just for this purpose is not great either.
Dictionaries can be nested to any depth. Dictionaries are mutable. All the keys in a dictionary must be of the same type. Dictionaries are accessed by key.
The Tuple method is similar to the above snippets, and while it is faster than the Dictionary<int, KeyValuePair<string, string>> , it is still nowhere near as fast as indexing directly into the collection to the desired value based on a hashed key, as is done in the MultiKeyDictionary class.
To remove an element from a nested dictionary, use the del() method.
I offer another choice:
Dictionary<Tuple<string, string, string>, string> pt;
Access to dictionary:
pt[Tuple.Create("id","group","part")]
UPDATE:
Value Tuples introduced in C# 7 is most eye-catching:
Dictionary<(string id, string group, string part), string> pt;
Access to dictionary:
pt[("id", "group", "part")]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With