Analogue of Python's defaultdict?
.net, c#
Solution
Here's a simple implementation:
public class DefaultDictionary<TKey, TValue> : Dictionary<TKey, TValue> where TValue : new()
{
public new TValue this[TKey key]
{
get
{
TValue val;
if (!TryGetValue(key, out val))
{
val = new TValue();
Add(key, val);
}
return val;
}
set { base[key] = value; }
}
}
And how you would use it:
var dict = new DefaultDictionary<string, int>();
Debug.WriteLine(dict["foo"]); // prints "0"
dict["bar"] = 5;
Debug.WriteLine(dict["bar"]); // prints "5"
Or like this:
var dict = new DefaultDictionary<string, List<int>>();
dict["foo"].Add(1);
dict["foo"].Add(2);
dict["foo"].Add(3);
Problem
Is there a .NET analogue of Python's `defaultdict`? I find it useful to write short code, eg. counting frequencies: ``` >>> words = "to be or not to be".split() >>> print words ['to', 'be', 'or', 'not', 'to', 'be'] >>> from collections import defaultdict >>> frequencies = defaultdict(int) >>> for word in words: ... frequencies[word] += 1 ... >>> print frequencies defaultdict(<type 'int'>, {'not': 1, 'to': 2, 'or': 1, 'be': 2}) ``` So ideally in C# I could write: ``` var frequencies = new DefaultDictionary<string,int>(() => 0); foreach(string word in words) { frequencies[word] += 1 } ```