Photo by Marc Najera on Unsplash

Maps vs Keyword Lists in Elixir

I recently went down a rabbit hole with a coworker, asking ourselves, “What is the difference between a map and a keyword list?” We knew that they both provide the similar seeming capabilities to store and access key-value information but were unsure of the underlying differences.

Consulting the docs on the Keyword module didn’t immediately clear this up for us:

“A keyword may have duplicated keys so it is not strictly a key-value data type. However most of the functions in this module behave exactly as a key-value so they work similarly to the functions you would find in the Map module.”

If a keyword list can pretty much be accessed as a map, then what is the difference, and what is the point of having different data structures?

Quick Reference of Differences

Similar Interface, Different Implementations

Maps and keyword lists are both ways of representing associative data, so Elixir provides many of the same functions for interacting with them as a nicety. For example, delete/2, get/3, has_key?/2, keys/3, values/1 can all be called on both maps and keyword lists (and there are many more). Not all languages provide this nice interface, allowing for list-only access for keyword lists.

It’s important to understand that the implementation of these functions differs because maps and keyword lists are, at the end of the day, different data structures. For a large dataset, it absolutely matters that Map.get is doing an actual hash lookup in logarithmic time, while Keyword.get is searching through a list in linear time.

This might explain why Elixir uses keyword lists for passing options but not a lot else. Almost any case in which you want to do a dictionary lookup, you will want to use a map.

--

--

Insights and explorations from the software development team making new things possible in additive manufacturing.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store