# NamedTuples vs Dict

**URL:** <https://discourse.julialang.org/t/namedtuples-vs-dict/13119>\
**Category:** New to Julia\
**Created:** [August 9, 2018, 9:42pm UTC](https://discourse.julialang.org/t/namedtuples-vs-dict/13119 "2018-08-09T21:42:45Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![daniel](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/daniel/32/6480_2.png) [@daniel](https://discourse.julialang.org/u/daniel)\
**Post date:** [August 9, 2018, 9:42pm UTC](https://discourse.julialang.org/t/namedtuples-vs-dict/13119/1 "2018-08-09T21:42:45Z")

</div>

I wondered about use cases of NamedTuples vs Dicts.  
Obviously one would choose a NamedTuple if the order of elements is important and a Dict if the keys have to be something else than a symbol, but are there any other situations where one is preferred over the other?

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [August 9, 2018, 10:23pm UTC](https://discourse.julialang.org/t/namedtuples-vs-dict/13119/2 "2018-08-09T22:23:07Z")

</div>

Small NamedTuples are much cheaper to construct than small Dicts:

```julia
julia> @btime (a=1, b=2)
  1.753 ns (0 allocations: 0 bytes)

julia> @btime Dict(:a => 1, :b => 2)
  102.756 ns (4 allocations: 608 bytes)

```

But on the other hand, NamedTuples cannot be changed after they are constructed, while you can add, delete, or change elements in a Dict easily.

So NamedTuples are great when you want to construct them very quickly and don’t need to modify the result after you create it, while Dicts are great when you want to create a mapping that you can update in the future.

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [August 9, 2018, 10:23pm UTC](https://discourse.julialang.org/t/namedtuples-vs-dict/13119/3 "2018-08-09T22:23:51Z")

</div>

Also, if you care about the order of the elements but you still want a mutable container, then check out `OrderedDict` from `DataStructures.jl`.

---

<div class="post-metadata">

**Author:** ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)\
**Post date:** [August 9, 2018, 10:38pm UTC](https://discourse.julialang.org/t/namedtuples-vs-dict/13119/4 "2018-08-09T22:38:03Z")

</div>

`NamedTuple` encodes it’s structure in the type, `Dict` encodes that in the value so every trade off between runtime and compile time computation applies here just like countless number of other cases in the language. It’s basically the same as choosing between `Tuple` and `Array`.
