I have one mapping initialized before constructor.

mapping(address  => uint) TokenValsByAddress;

This mapping stores 10 addresses. After some operations , I got new mapping with same 10 addresses of TokenValsByAddress and new 2 address.

mapping(address  => uint) NewMapping;

Now I want to assign NewMapping to TokenValsByAddress.

I get an error when I do below assignment.

TokenValsByAddress = NewMapping;

Error : Mappings can not be assigned to.

What should I do to update TokenValsByAddress ?


You cannot directly duplicate/copy a mapping in Solidity.

Mappings can grow to be extremely large and a copy operation could easily exceed the block gas limit.

See this answer for some more details about the gas limits: https://ethereum.stackexchange.com/a/24519/3573

A strategy for duplicating a mapping is to keep an array of each key added to it. Then loop that array and assign the value from the old mapping to the new one.

pragma solidity ^0.4.14;

contract Mapping {
    mapping(address => uint256) map;
    mapping(address => uint256) dupe;
    address[] keys;

    function add(uint256 value) {
        map[msg.sender] = value;

    function duplicate() {
        for(uint256 i; i < keys.length; i++) {
            dupe[keys[i]] = map[keys[i]];

The above code works, however it will pretty quickly hit the gas limit described above, plus some other limitations.

Looping a mapping in Solidity is generally considered an anti-pattern and should be avoided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.