How to pretty print nested dicts (or other data structures) in julia? For instance this:
xx = Dict(
"a"=>77,
"b"=>55,
"c"=> Dict(
44=>"alfa",
55=>"beta",
66=>Dict(
"x"=>999,
"y"=>888
)
)
)
The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable.
Pretty Print a Dict in Python with pprint Using this library, we can print out more nicely formatted data structures, including dictionaries. The pprint library allows us to specify a number of different parameters, including the following: indent : the number of spaces to indent each line, where the default value is 1.
You could use JSON.jl and the mostly undocumented indent
argument, eg
julia> using JSON
julia> print(json(xx,4))
{
"c": {
"55": "beta",
"66": {
"x": 999,
"y": 888
},
"44": "alfa"
},
"b": 55,
"a": 77
}
"Pretty" lies, of course, in the eye of the beholder, but why not simply do something like this? (I am not aware of a preimplemented function)
function pretty_print(d::Dict, pre=1)
for (k,v) in d
if typeof(v) <: Dict
s = "$(repr(k)) => "
println(join(fill(" ", pre)) * s)
pretty_print(v, pre+1+length(s))
else
println(join(fill(" ", pre)) * "$(repr(k)) => $(repr(v))")
end
end
nothing
end
Your example above would be printed as follows.
julia> pretty_print(xx)
"c" =>
55 => "beta"
66 =>
"x" => 999
"y" => 888
44 => "alfa"
"b" => 55
"a" => 77
Alternative version that pretty prints level by level
function pretty_print2(d::Dict, pre=1)
todo = Vector{Tuple}()
for (k,v) in d
if typeof(v) <: Dict
push!(todo, (k,v))
else
println(join(fill(" ", pre)) * "$(repr(k)) => $(repr(v))")
end
end
for (k,d) in todo
s = "$(repr(k)) => "
println(join(fill(" ", pre)) * s)
pretty_print2(d, pre+1+length(s))
end
nothing
end
Output:
julia> pretty_print2(xx)
"b" => 55
"a" => 77
"c" =>
55 => "beta"
44 => "alfa"
66 =>
"x" => 999
"y" => 888
Maybe not very general and performant but you get the idea.
EDIT: I forgot to print the keys of subdictionaries. I'll leave it to the reader to adjust the function in this regard.
EDIT2: Per request, I adjusted the original version to also print keys of subdictionaries and added a (maybe prettier version) that outputs level by level.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With