Display of dictionary contents to file

,

Hi,
I have a general question regarding dictionaries display. I have a dictionary that has several fields, some of which are instances of types I’ve created that conatin really large arrays of numbers. When I print its contents to screen I get things like this

display(INP_PT_LB)

OrderedDict{Any, Any} with 24 entries:
  "kind"             => Float64
  "rbm"              => RBM_net{Float64}(Binary_01(), 180, 20, #undef, #undef, …
  "Nβ"               => 1000
  "T0"               => 2000.0
  "λ"                => 0.95
  "Nflip"            => 1
  "α"                => [0.315438, 0.356355, 0.84791, 0.873976, 0.925063, 0.878…
  "u_ini"            => Bool[1 0 … 1 1; 1 0 … 0 1; … ; 0 1 … 1 0; 1 1 … 0 0]
  "xx"               => Bool[0 0 … 0 1; 0 1 … 1 0; … ; 1 0 … 1 0; 0 1 … 1 0]
  "NMC"              => 100
  "Nepochs"          => 1000
  "Nbest"            => 1000
  "IOUT"             => "/tmp/dalenomas.res"
  "Print_Bo"         => true
  "Print_List_Best"  => true
  "Iters_Print_Best" => 10
  "List_Best"        => false
  "List_uBest"       => false
  "List_xBest"       => false
  "List_αBest"       => 0.0
  "Bmax"             => 0
  "umax"             => 0
  "xmax"             => 0
  "αmax"             => 0

which is very nice because large arrays are summarized in one line, and I do not need to see every single number at this point. So display is doing the trick for me.
But now I want to store that same exact form to an ouput strem IO I have opened with
something like

IO = open("/tmp/dale.dat","w")

So the question is: is it possible to redirect the contents of display() to IO?
Notice a println(IO,…) or similar does not work, as it insists in printing the whole (laaaarge) arrays.

Thanks a lot.

Use the 3-argument show, which is what display calls under the hood:

show(io, "text/plain", INP_PT_LB)

(I would also call your variable io rather than IO, since IO is a type in Julia and it is confusing to shadow it with a variable.)

If you want to limit the output, you wrap the io stream in an IOContext, e.g as IOContext(io, :limit => true), where the :limit option causes it to truncate large outputs. This works for both println (which calls 2-argument show) and for 3-argument show (although the two output formats may differ).

The next version of the manual will have a summary of how all these output functions relate, which you can view now on github.

2 Likes

TOML prints dicts in a very readable manner as well:

julia> using TOML

julia> d = Dict("a" => [1,2,3,4,5], "b" => 1.0)
Dict{String, Any} with 2 entries:
  "b" => 1.0
  "a" => [1, 2, 3, 4, 5]

julia> open("dict.txt", "w") do io
           TOML.print(io, d)
       end

shell> more dict.txt
b = 1.0
a = [1, 2, 3, 4, 5]


Thanks people, these hints where really helpful and now I got the desired printing behaviour :slight_smile: