Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 47 ยท Language Basics

Mappings

Learn Solidity mappings: key-value storage, default values, nested mappings, why you cannot loop over them, and the pattern for tracking keys.

A mapping is Solidity's key-value store, and it is the most used data structure in contracts. Token balances, voting records, ownership, allowances: nearly all of them are mappings from an address (or an ID) to some value. If you know a dictionary in Python or a Map in JavaScript, the idea is familiar, but a mapping behaves differently in a few ways that matter for correctness and for gas.

This lesson shows how to declare and use mappings, why you cannot loop over one, and the standard pattern for keeping a list of keys beside it.

A mapping in one picture

Key Any value type, bytes or string.
Value Any type, even another mapping.
Default Every key already "exists" with a zero value.

There is no such thing as a missing key.

1 / 2

Declaring and using a mapping

The syntax is mapping(KeyType => ValueType):

SOLIDITY
mapping(address => uint256) public balances;

function deposit() external payable {
    balances[msg.sender] += msg.value;
}

function myBalance() external view returns (uint256) {
    return balances[msg.sender];
}

Marking it public generates a getter function balances(address) that takes the key and returns the value. Reading and writing use square brackets. There is no put, get or has.

Keys can be any built-in value type (address, uint, bool, bytes32, enums) and also bytes and string. They cannot be another mapping, a struct or an array. Values can be anything, including structs, arrays and other mappings.

Every key exists

A mapping does not store keys at all. Conceptually, every possible key already maps to the default value of the value type: 0 for numbers, false for bool, the zero address for address, and an all-zero struct for structs. Reading a key that was never written does not revert and does not return "not found". It returns zero.

SOLIDITY
mapping(address => bool) public isMember;
// isMember[someone] is false until you set it to true

This has one consequence you must design around: you cannot tell "never set" from "set to zero". If 0 is a legitimate stored value, add a separate flag, such as an exists boolean inside a struct, or store the data as value + 1.

Under the hood the EVM does not keep a table of keys either. The value for a key lives at a storage position computed from the key and the mapping's slot (a hash of the two). That is why lookups are fast and constant-cost, and also why the contract has no way to list the keys.

Nested mappings and structs as values

A value can be another mapping, which gives you two-level lookups. The standard example is a token allowance: how much owner lets spender use.

SOLIDITY
mapping(address => mapping(address => uint256)) public allowance;

function approve(address spender, uint256 amount) external {
    allowance[msg.sender][spender] = amount;
}

You read it left to right: first by owner, then by spender. A mapping can also hold structs, which is how you store several fields per key:

SOLIDITY
struct Account {
    uint256 balance;
    uint64 lastSeen;
    bool exists;
}

mapping(address => Account) public accounts;

To update one field, write it directly: accounts[who].balance += 1;. Because the mapping lives in storage, this edits the stored struct in place. See Strings, Bytes, Arrays and Structs for the pointer rules.

No iteration: track the keys yourself

Since a mapping has no key list, the contract cannot answer "who are all my members?" The common solution is to keep an array of keys next to the mapping and update both together. A typical version also remembers each key's position, so removal is cheap:

SOLIDITY
mapping(address => uint256) public balances;
mapping(address => uint256) private position;   // index + 1, so 0 means "not in the list"
address[] public holders;

function _setBalance(address who, uint256 amount) internal {
    if (position[who] == 0 && amount > 0) {
        holders.push(who);
        position[who] = holders.length;
    }
    balances[who] = amount;
}

function _remove(address who) internal {
    uint256 idx = position[who] - 1;
    address last = holders[holders.length - 1];
    holders[idx] = last;           // swap and pop
    position[last] = idx + 1;
    holders.pop();
    delete position[who];
    delete balances[who];
}

Note the trick of storing index + 1: it lets you use 0 to mean "not present", which solves the default-value problem above. A single swap-and-pop removes an entry without shifting the whole array.

Even with this pattern, think twice before looping over holders inside a transaction. The array can grow without limit, and a loop over it costs more gas the longer it gets, until it no longer fits in a block. Off-chain code can read the list and process it in pieces, or you can design the contract so that each user claims their own share and nothing needs a global loop. The lesson on Control Flow, require, revert and Custom Errors returns to loop costs.

delete and mappings

delete balances[who] resets that one entry to its default value, which clears the storage slot (and can earn a small gas refund). What you cannot do is delete balances on the whole mapping; the compiler refuses, because it has no key list to walk. The same applies to a struct that contains a mapping: deleting the struct resets its other fields but leaves the mapping's entries untouched. If you need a full reset, change what the mapping is keyed by, for example a round number: mapping(uint256 => mapping(address => uint256)), and move to the next round.

A mapping stand-in with key tracking

A JavaScript Map has methods that Solidity mappings lack, so the stand-in below deliberately hides them. It only offers get and set (with defaults, like a mapping) and keeps its own key list just as the contract pattern does.

JS Default values and the missing 'exists'

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Bob and Carol cannot be told apart from the value alone, which is exactly why contracts add an exists flag or the index + 1 trick. Now the key-tracking pattern, including removal by swap and pop.

JS A mapping plus a key list

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What is real: default values, the lack of a key list, the index + 1 pattern and swap and pop. What is the stand-in: a JavaScript Map that really does store keys (a Solidity mapping does not, it hashes key and slot), and no gas. The stand-in's delete also removes the key, while a real delete sets the entry back to its default.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does balances[someone] return if someone was never written to?

    A mapping has no concept of a missing key. Every key maps to the zero value until written, so you cannot tell never-set from set-to-zero.
  2. 2. Why can a contract not loop over all keys of a mapping?

    The EVM computes each value's slot from the key and mapping position. No list of keys exists unless you maintain one yourself in an array.
  3. 3. What is the purpose of storing index + 1 in a position mapping?

    Because unset keys read as 0, a real index of 0 would be indistinguishable from absent. Offsetting by one frees 0 as the 'absent' marker.
  4. 4. Which type is NOT allowed as a mapping key?

    Keys can be value types, bytes or string. Mappings, arrays and structs are not allowed as keys, although they can be values.

Summary

  • mapping(K => V) stores values by key; reading uses m[key] and a public mapping gets a getter that takes the key.
  • Every key already exists with the zero value, so add a flag or an index + 1 trick when zero is meaningful.
  • Nested mappings (m[a][b]) model allowances and other two-part lookups; values can also be structs.
  • Mappings cannot be iterated, measured or cleared; keep a separate key array when you need a list.
  • delete m[key] resets one entry; avoid unbounded loops over a key array inside transactions.

Next: Functions and Visibility.