dictionarytuplesjulianamedtuple

Dictionaries vs NamedTuples


Aside that Dictionaries are mutable and NamedTuple not, that NamedTuple can be retrieved by position and a bit of different notation, are there other significant differences between Dictionaries and NamedTuples in Julia ? When to use one or the other ?

They seem pretty similar:

# Definition
d  = Dict("k1"=>"v1", "k2"=>"v2")
nt = (k1="v1", k2="v2")

# Selection by specific key
d["k1"]
nt.k1

# Keys
keys(d)
keys(nt)

# Values
values(d)
values(nt)

# Selection by position
d[1] # error
nt[1]

Solution

  • Think of NamedTuple as an anonymous struct in Julia not a Dict. In particular storing heterogeneous types in NamedTuple is type stable.

    Note that this is also a major difference in thinking between Python and Julia. In Julia if you want your code to be fast you usually care about type inference.