Custom fancy printing of non-empty Dict?

For a project, I would like the output of a Dict (and, more specifically, an OrderedDict) containing a type specific to my project to be a custom fancy print instead of an overview of the dictionary’s contents.

When I apply this function:

function Base.show(io::IO, dictionary::Dict{Int64, SpecificType}())
    print(io, "A dictionary containing ", length(dictionary), " items.")
end

However, this function works only when using print(dictionary) or show(dictionary), or when the dictionary is empty. Otherwise, when the output is a non-empty dictionary, the print is:

Dict{Int64, SpecificType} with x entries:

Is there a way to change this behavior?

If you want an AbstractDict that prints differently it might be best to make your own MyDict struct, perhaps containing a d::Dict field and forwarding methods to it, but defining its own special show method.

3 Likes

I agree with @jar. It’s better to create your own AbstractDict that wraps a regular Dict.

That being said, the behavior you are observing is odd, and I can’t explain it. Here’s a complete example:

Setup:

struct Foo end

function Base.show(io::IO, d::Dict{Int64, Foo})
    println(io, "A dictionary containing ", length(d), " items.")
end

d = Dict(1 => Foo());

Printing:

julia> print(d)
A dictionary containing 1 items.

julia> show(d)
A dictionary containing 1 items.

julia> Dict{Int, Foo}()
A dictionary containing 0 items.

julia> d
Dict{Int64, Foo} with 1 entry:
  1 => Foo()
1 Like

You need to implement the 3-arg show. Continuing from @CameronBieganek’s MWE:

julia> function Base.show(io::IO, ::MIME"text/plain", d::Dict{Int64, Foo})
           println(io, "A dictionary containing ", length(d), " items.")
       end

julia> d
A dictionary containing 1 items.
3 Likes