Introduction to Maps
Introduction to Maps
Welcome back! In the previous lessons, we discussed lists and tuples in Elixir, both of which are fundamental data structures for storing and managing data. In this unit, we will focus on another essential data structure: maps.
Maps are incredibly useful when you need to store key-value pairs. They provide an efficient way to associate values with unique keys, making data retrieval swift and intuitive. Mastering maps will significantly enhance your ability to work with structured data in Elixir.
What You'll Learn
In this lesson, we will explore various operations you can perform with maps in Elixir:
- Creating a map
- Inspecting a map
- Accessing elements within a map
Let's start by creating and inspecting a map:
The above code snippet demonstrates how to create a map and inspect its contents. The IO.inspect(map) line will print %{name: "Elixir", age: 10} to the console.
A key difference between maps and other Elixir data structures like lists and tuples is that maps use keys to access data, whereas lists and tuples use positions. Lists and tuples are better for ordered data, while maps are great when you want to label each piece of data with a meaningful key.
Let's also understand what are the ways to access the values from the map:
- Using square brackets
[:key]syntax: With this syntax, you can access the value associated with a specific key by providing the key in square brackets as an atom. For example,map[:name]will return the value"Elixir"associated with the key:name. Notice that the key is an atom, which is a unique identifier in Elixir – even if the keys don't look like atoms, they are converted to atoms internally. - Using dot notation
.keysyntax: You can also access the value associated with a key using the dot notation. For example,map.agewill return the value10associated with the key:age.
Notice, that you can explicitely use strings as keys as follows:
Notice that in this case, the keys are strings, and you can access the values using the string keys. However, you cannot access the values using the dot notation because the keys are not atoms. Similarly, you cannot access the values using square brackets with atom keys.
