JULIA / CHAPTER 05

Dictionaries, tuples, and named values

Intermediate

Choose a container from its access and mutation requirements.

By the end of this chapter

  • Use dictionary keys and defaults
  • Represent fixed records with named tuples
  • Avoid depending on dictionary iteration order

The idea

A dictionary maps keys to values and is useful when lookup depends on an identifier rather than a position. Indexing with a missing key raises an error, while get can supply an explicit default. Updating a key replaces its stored value, and haskey asks whether the key exists. A counting algorithm often combines a default of zero with an increment for each observed item.

A tuple groups a fixed sequence of values, and a named tuple adds readable field names. Their structure is immutable, though a mutable object stored inside them can still change. Use a vector when the sequence itself must grow, and a dictionary when the collection of keys changes. Do not treat dictionary iteration order as a sorted presentation contract; sort keys explicitly when the output needs a stable order.

Julia example
counts = Dict("bug" => 2)
counts["task"] = get(counts, "task", 0) + 1
counts["bug"] = get(counts, "bug", 0) + 1
summary = (bugs = counts["bug"], tasks = counts["task"])
println(summary.bugs)
println(summary.tasks)
Result
3
1

The absent task key starts from zero. The existing bug key increments from two, and the named tuple records the resulting values with readable field names.

Try it yourself

Count words in a vector into a dictionary, then print keys in alphabetical order with their counts.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What does this print?
d = Dict("a" => 4)
println(get(d, "b", 9))
println(haskey(d, "b"))