Programming Search⌘K

Maps and sets

Collections looked up by key: maps, dictionaries, hash tables and sets.

Concepts

  • Map and dictionary

    A map, or dictionary, stores pairs of a key and a value, with each key at most once. A program uses the key to find, change or remove its value.

    intro
  • Set

    A set holds distinct values with no order. Its main operation is a test of whether a value is in the set, and it also gives union, intersection and difference.

    intro
  • Hash table

    A hash table stores keys in an array of buckets and uses the hash code of a key to find its bucket. Lookup, insert and remove take constant time on average.

    core
  • Insertion-ordered map

    An insertion-ordered map gives its keys back in the order in which they were added. Python dict, JavaScript Map and Java LinkedHashMap work this way, and Go and C++ maps do not.

    core
  • Ordered map

    An ordered map keeps its keys sorted. It finds a key in logarithmic time, and it also gives the smallest key, the next key after a value and all keys in a range.

    core
  • Multimap

    A multimap is a map in which one key can have more than one value. Most languages build it as a map whose values are lists, and C++ and C# have types for it.

    advanced
  • Multiset

    A multiset is a set in which an item can appear more than once. Programs store it as a map from each item to its count, as Python Counter does.

    advanced

Tasks

  • Create a map

    Put key and value pairs in a new map, so a later pair replaces the value of its key, delete some keys, and list the entries in key order.

    10 languagesintro
  • Create a set

    Create an empty set, add and remove items and test membership, by adding each word that is not in the set and removing each word that is in it.

    10 languagesintro
  • Do set operations

    Find the union, intersection, difference and symmetric difference of two sets of words, and test whether one set is a subset of the other.

    10 languagesintro
  • Iterate over a map

    Walk the entries of a map in key order to print one line for each entry, then walk the values to add them up.

    10 languagesintro
  • Merge two maps

    Make a new map with the entries of two maps, where the value of the second map wins for a key in both, and keep the two maps unchanged.

    10 languagesintro
  • Use a map with a default value

    Read keys from a map and use a fallback value for a key that is not in the map, without adding the key and without mixing up a missing key with a stored 0.

    10 languagesintro
  • Use a custom key in a map

    Use a point type as the key of a map, with equality and a hash that agree, so that two equal points find one entry.

    10 languagescore