Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two dictionaries without looping?

People also ask

Can you merge two dictionaries?

You can merge two dictionaries by iterating over the key-value pairs of the second dictionary with the first one.

How do I merge two dictionaries in a single expression?

Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.


var d3 = d1.Concat(d2).ToDictionary(x => x.Key, x => x.Value);

You can use Concat:

Dictionary<string, object> d1 = new Dictionary<string, object>();
d1.Add("a", new object());
d1.Add("b", new object());
Dictionary<string, object> d2 = new Dictionary<string, object>();
d2.Add("c", new object());
d2.Add("d", new object());

Dictionary<string, object> d3 = d1.Concat(d2).ToDictionary(e => e.Key, e => e.Value);

foreach (var item in d3)
{
    Console.WriteLine(item.Key);
}

First up, it's not possible without looping. Whether that loop is done in a (extension) method is irrelevent, it still requires a loop.

I'm actually going to recommend doing it manually. All the other answers given require using two extention methods (Concat - ToDictionary and SelectMany - ToDictionary) and thus looping twice. If you are doing this to optimise your code, it will be faster to do a loop over dictionary B and add it's contents to dictionary A.

Edit: After further investigation, the Concat operation would only occur during the ToDictionary call, but I still think a custom extension method would be more efficient.

If you want to reduce your code size, then just make an extension method:

public static class DictionaryExtensions
{
    public static IDictionary<TKey,TVal> Merge<TKey,TVal>(this IDictionary<TKey,TVal> dictA, IDictionary<TKey,TVal> dictB)
    {
        IDictionary<TKey,TVal> output = new Dictionary<TKey,TVal>(dictA);

        foreach (KeyValuePair<TKey,TVal> pair in dictB)
        {
            // TODO: Check for collisions?
            output.Add(pair.Key, Pair.Value);
        }

        return output;
    }
}

Then you can use it by importing ('using') the DictionaryExtensions namespace and writing:

IDictionary<string,objet> output = dictA.Merge(dictB);

I have made the method act like the objects are immutable, but you could easily modify it to not return a new dictionary and just merge into dictA.


var result = dictionaries.SelectMany(dict => dict)
             .ToDictionary(pair => pair.Key, pair => pair.Value);