Nested Dictionary Structures
Explore how to work with nested dictionary structures in Elixir to efficiently update and access data within maps, keyword lists, and structs. Learn to use functions like put_in, update_in, get_in, and dynamic nested accessors for clean and maintainable code.
We'll cover the following...
Introduction
The various dictionary types let us associate keys with values. But those values can themselves be dictionaries. For example, we may have a bug-reporting system. We could represent this using the following:
defmodule First.MixProject do
use Mix.Project
def project do
[
app: :first,
version: "0.1.0",
elixir: "~> 1.12",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
def hello do
[
IO.puts("Hello")
]
end
end
We may create a report for the above code as report = %BugReport{owner: %Customer{name: "Dave", company: "Pragmatic"}, details: "broken"}.
The owner attribute of the report is itself a Customer struct.
We can access nested fields using regular dot notation:
iex> report.owner.company
"Pragmatic"
But now our customer complains the company name is incorrect. It should be PragProg. Let’s fix it using the code below:
iex> report = %BugReport{ report | owner:
%Customer{ report.owner | company: "PragProg" }}
%BugReport{details: "broken",
owner: %Customer{company: "PragProg", name: "Dave"},
severity: ...