Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท Data Structures

Maps in Clojure: assoc, get, merge and Keywords as Functions

Learn Clojure maps: literals, get and keyword lookup, assoc, dissoc, update, merge, keys and vals, iterating entries, select-keys, group-by, frequencies and map vs sorted-map.

The map is the workhorse of Clojure. Where other languages define classes with fields, Clojure programs usually pass around plain maps with keyword keys: {:name "Ada" :age 36}. Maps are immutable, compare by value and come with a rich set of functions. This lesson shows how to create, read, update and reshape them.

Creating maps

CLOJURE
{:name "Ada" :age 36 :languages ["Analytical Engine" "Clojure"]}
(hash-map :a 1 :b 2)           ; {:a 1, :b 2}
(array-map :z 1 :a 2)          ; keeps insertion order for small maps
(zipmap [:a :b :c] [1 2 3])    ; {:a 1, :b 2, :c 3}
(into {} [[:a 1] [:b 2]])      ; {:a 1, :b 2}
(sorted-map :b 2 :a 1)         ; {:a 1, :b 2} ordered by key

Any value can be a key, but keywords are by far the most common. Keys must be unique; a duplicate key in a literal is a compile error. The order of a regular map is not guaranteed, so do not depend on it. Use sorted-map when you need the entries ordered by key.

Reading values

CLOJURE
(def person {:name "Ada" :age 36})

(get person :name)            ; "Ada"
(get person :email)           ; nil
(get person :email "n/a")     ; "n/a"   with a default
(:name person)                ; "Ada"   keyword as a function
(:email person "n/a")         ; "n/a"
(person :age)                 ; 36      a map is a function of its keys
(contains? person :name)      ; true
(contains? {:a nil} :a)       ; true    the key exists even if the value is nil
(find person :age)            ; [:age 36]  the entry, or nil
(keys person)                 ; (:name :age)
(vals person)                 ; ("Ada" 36)
(count person)                ; 2

The keyword-as-function form (:name person) is the most idiomatic way to look up a value and is why keywords are preferred to strings as keys. It also works nicely with higher-order functions: (map :name people) extracts the name of every person in a list.

For string keys use get or call the map: (m "key"). A string is not callable, so ("key" m) would fail.

JS Stand-in: map access with defaults

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

No output.

Updating maps

Every update returns a new map:

CLOJURE
(assoc person :email "[email protected]")      ; adds or replaces a key
(assoc person :age 37 :city "London")        ; several pairs at once
(dissoc person :age)                         ; removes a key
(update person :age inc)                     ; apply a function to a value
(update person :tags conj "math")            ; works with missing keys: conj onto nil
(merge person {:age 40 :city "London"})      ; later maps win
(merge-with + {:a 1 :b 2} {:a 10 :c 3})      ; {:a 11, :b 2, :c 3}
(select-keys person [:name])                 ; {:name "Ada"}
(rename-keys person {:name :full-name})      ; needs clojure.set
person                                       ; unchanged

update is the tool to reach for when the new value depends on the old one: increment a counter, add to a collection, append to a string. Its form is (update m key f & args) which calls (f old-value & args).

CLOJURE
(update {:visits 1} :visits + 5)      ; {:visits 6}
(update {} :tags (fnil conj []) "x")  ; {:tags ["x"]}

fnil wraps a function so that a nil argument is replaced by a default; here it turns a missing :tags into an empty vector before conj.

Iterating over a map

A map behaves as a sequence of [key value] entries. Functions like map, filter, reduce and for accept it directly:

CLOJURE
(def prices {:apple 1.2 :pear 0.8 :plum 2.0})

(for [[fruit price] prices]
  (str (name fruit) ": " price))
;; => ("apple: 1.2" "pear: 0.8" "plum: 2.0")

(reduce + (vals prices))                   ; 4.0
(into {} (map (fn [[k v]] [k (* v 2)]) prices))   ; doubles every price
(update-vals prices #(* % 2))              ; Clojure 1.11 shortcut
(update-keys prices name)                  ; {"apple" 1.2, ...}
(filter (fn [[_ v]] (> v 1)) prices)       ; ([:apple 1.2] [:plum 2.0])

The destructuring [[fruit price] prices] pulls each entry apart. Note that map over a map returns a sequence, so wrap it in (into {} ...) to get a map back. update-vals and update-keys were added in Clojure 1.11 and handle the common cases directly.

JS Stand-in: transforming a map's values

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

No output.

Maps from collections: frequencies and group-by

Two functions turn a sequence into a map:

CLOJURE
(frequencies ["a" "b" "a" "c" "a"])
;; => {"a" 3, "b" 1, "c" 1}

(group-by count ["one" "two" "three" "four"])
;; => {3 ["one" "two"], 5 ["three"], 4 ["four"]}

(group-by even? (range 6))
;; => {true [0 2 4], false [1 3 5]}

group-by takes a function and builds a map from each result of that function to a vector of the items. Together with reduce, these two replace most hand-written counting loops.

Working with maps

Read get, keyword call, contains?
Change assoc, dissoc, update, merge
Transform update-vals, into, select-keys
Summarise frequencies, group-by

Each call returns a new map.

1 / 2

Records and namespaced keys

Plain maps are flexible but have no declared shape. Two ways to add structure:

  • Namespaced keywords such as :user/name and :order/total avoid clashes and document where data comes from.
  • Records (defrecord) define a named type with fixed fields that still behaves like a map; they are covered with protocols later in the course.
CLOJURE
{:user/name "Ada" :user/email "[email protected]"}
(:user/name {:user/name "Ada"})    ; "Ada"

Common mistakes

  • Expecting a stable order from hash-map or large maps. Use sorted-map or sort the entries.
  • Using (map f a-map) and expecting a map back.
  • Confusing a missing key with a nil value; use contains? to tell them apart.
  • Mixing string and keyword keys: (:name {"name" "Ada"}) is nil.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (:email {:name "Ada"}) return?

    Looking up a missing key returns nil (or the default if you pass one).
  2. 2. Which call increments the :count value of a map m?

    update applies a function (here inc) to the existing value of the key.
  3. 3. What does (merge {:a 1 :b 2} {:b 9}) return?

    merge combines maps and the later map wins on duplicate keys.
  4. 4. Which function builds a map from each result to the list of matching items?

    group-by applies a function to each item and groups items with the same result.

Summary

  • Maps are the standard way to model entities: {:name "Ada" :age 36}.
  • Read with get or the keyword-as-function form (:key m), and use a default as a second argument.
  • Update with assoc, dissoc, update, merge and select-keys; the original map is never changed.
  • Iterate by destructuring entries; into {} turns a sequence of pairs back into a map; update-vals and update-keys shortcut common transforms.
  • frequencies and group-by summarise a collection into a map.

Next: Sets