Seeking better dictionary initialization

I recently answered a question here with a PowerShell dictionary that used "ContainsKey" to decide whether to define a key value or add to it if necessary. I do that a lot - usually in C#, Python, R, or PowerShell these days, and I tire of it.

Is there a language - or even a library - that could do the following PowerShell code block in a single line?

  if ($sums.ContainsKey($skey))
  {
        $sums[$skey] += $sval 
  }
  else
  {
        $sums[$skey] = $sval 
  }
Jon Skeet
people
quotationmark

ConcurrentDictionary in .NET will allow you to do that, yes:

sums.AddOrUpdate(key, value, (k, v) => v + value);

You should be able to use that (with syntax changes, obviously) in PowerShell, too.

Alternatively, if you want to do this for plain Dictionary in .NET, you could add an extension method:

public static void AddOrUpdate<TKey, TValue>(
    this Dictionary<TKey, TValue> dictionary,
    TKey key,
    TValue addValue,
    Func<TKey, TValue, TValue> updateValueFactory)
{
    TValue existing;
    if (dictionary.TryGetValue(key, out existing))
    {
        dictionary[key] = updateValueFactory(key, existing);
    }
    else
    {
        dictionary[key] = addValue;
    }
}

This is written to have the same effective signature as the ConcurrentDictionary method; if you only ever need a Func<TValue, TValue> for the update factory, you could change it accordingly.

I would imagine you could take the same approach in Python with a helper method - I don't know enough about Python to say whether you could do something like the extension method.

people

See more on this question at Stackoverflow