Pair out of nowhere (I wanted a dictionary)

Pairs are driving me a little bit crazy here. I don’t really understand the difference between a Dictionary and a Pair, and I don’t mentally see how a Dictionary type is inadequate. See this example. I’m trying to create a second Dictionary within the first dictionary, but I am somehow creating a Pair even though I am using the exact same syntax to create a Dictionary. Please help. What am I doing wrong?

julia> orderList = Dict{Int,Dict{Int,Int}}()
Dict{Int64,Dict{Int64,Int64}} with 0 entries

julia> push!(orderList, 2222201 => Dict())
Dict{Int64,Dict{Int64,Int64}} with 1 entry:
  2222201 => Dict{Int64,Int64}()

julia> orderList[2222201] = 1 => 22222
ERROR: MethodError: Cannot `convert` an object of type Pair{Int64,Int64} to an object of type Dict{Int64,Int64}
Closest candidates are:
  convert(::Type{T<:AbstractDict}, ::T<:AbstractDict) where T<:AbstractDict at abstractdict.jl:487
  convert(::Type{T<:AbstractDict}, ::AbstractDict) where T<:AbstractDict at abstractdict.jl:490
  convert(::Type{S}, ::T<:(Union{CategoricalString{R}, CategoricalValue{T,R} where
T} where R)) where {S, T<:(Union{CategoricalString{R}, CategoricalValue{T,R} where
T} where R)} at C:\Users\dburch.CSWG\.juliapro\JuliaPro_v1.0.4.1\packages\CategoricalArrays\JFETm\src\value.jl:91
  ...
Stacktrace:
 [1] setindex!(::Dict{Int64,Dict{Int64,Int64}}, ::Pair{Int64,Int64}, ::Int64) at .\dict.jl:381
 [2] top-level scope at none:0
orderList[2222201] = Dict(1 => 22222)
2 Likes

You can think of a dictionary as a collection of pairs.

julia> d = Dict{Int, Int}()
Dict{Int64,Int64} with 0 entries

# eltype(d) gives the type of each *element* of d:
julia> eltype(d)
Pair{Int64,Int64}

The syntax => constructs a Pair:

julia> typeof(1 => 2)
Pair{Int64,Int64}

You can construct a dictionary from one or more pairs:

julia> d = Dict(1 => 2, 3 => 4, 5 => 6)
Dict{Int64,Int64} with 3 entries:
  3 => 4
  5 => 6
  1 => 2

but a pair is not the same as a dictionary in the same way that an Int is not the same as a Vector{Int}.

So in your example, you need:

julia> orderList[2222201] = Dict(1 => 2222)
Dict{Int64,Int64} with 1 entry:
  1 => 2222

or

julia> orderList[2222201][1] = 2222
2222
8 Likes