Equivalent of Python's dict.update for STL maps in C++ dict objects in Python have an update method that can be used to extend one dictionary with all items from another, possibly overwriting entries that already exist.  I find this function very useful from time to time.

The associative containers from the C++ standard library (std::map and std::unordered_map) do not provide a direct analogue for this functionality so I wrote the following utility functions.

Comments regarding any aspect of the code are welcome.

#include &lt;cassert&gt;
#include &lt;utility&gt;

namespace codereview
{

    template &lt;typename DictT&gt;
    void update(DictT&amp; dst, const DictT&amp; src)
    {
        for (const auto&amp; [key, value] : src) {
            dst.insert_or_assign(key, value);
        }
    }

    template &lt;typename DictT&gt;
    void update(DictT&amp; dst, DictT&amp;&amp; src) noexcept
    {
        // Equal allocators are a precondition for splicing nodes
        assert(src.get_allocator() == dst.get_allocator());
        dst.merge(src);
        while (!src.empty()) {
            auto node = src.extract(src.cbegin());
            dst.extract(node.key());
            dst.insert(std::move(node));
        }
    }

}  // namespace codereview
You're not thinking laterally here.  If you std::swap() your two inputs, then you can merge() the original into the new, and the contents of the new map will prevail.

Here's what I mean:

namespace codereview
{
    template &lt;typename DictT&gt;
    void update(DictT&amp; dst, DictT src)
    {
        std::swap(dst, src);
        dst.merge(src);
    }

}  // namespace codereview




// Test
#include &lt;iostream&gt;
#include &lt;map&gt;

template&lt;typename Map&gt;
void print(const Map&amp; x)
{
    for (auto const&amp; i: x)
        std::cout &lt;&lt; i.first &lt;&lt; "=" &lt;&lt; i.second &lt;&lt; " ";
    std::cout &lt;&lt; std::endl;
}

int main()
{
    using Map = std::map&lt;int, const char*&gt;;
    Map a { {0, "zero"}, {1, "one"} };
    const Map b { {0, "nothing"}, {2, "two"}};

    print(a);

    // test lvalue argument
    codereview::update(a, b);
    print(a);

    // test rvalue argument
    codereview::update(a, Map{{3, "three"}, {0, "nada"}});
    print(a);
}


Output

0=zero 1=one 
0=nothing 1=one 2=two 
0=nada 1=one 2=two 3=three 


Note that I changed the method signature to accept src by copy - the compiler will move-construct into src if it can, but if not, we'll need a copy so that we don't perturb the caller's version when we swap.