如何在julia中打印嵌套的dicts?

时间:2018-01-10 20:45:11

标签: julia

如何在julia中打印嵌套dicts(或其他数据结构)?例如:

xx = Dict(
    "a"=>77, 
    "b"=>55,
    "c"=> Dict(
        44=>"alfa",
        55=>"beta",
        66=>Dict(
            "x"=>999,
            "y"=>888
        )
    )
)

2 个答案:

答案 0 :(得分:9)

您可以使用JSON.jl和大多数未记录的indent参数,例如

julia> using JSON

julia> print(json(xx,4))
{
    "c": {
        "55": "beta",
        "66": {
            "x": 999,
            "y": 888
        },
        "44": "alfa"
    },
    "b": 55,
    "a": 77
}

答案 1 :(得分:5)

“漂亮”当然是在旁观者的眼中,但为什么不简单地做这样的事情呢? (我不知道预先实现的功能)

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

上面的示例将打印如下。

julia> pretty_print(xx)
 "c" =>
         55 => "beta"
         66 =>
                "x" => 999
                "y" => 888
         44 => "alfa"
 "b" => 55
 "a" => 77

可逐级打印的替代版本

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

输出:

julia> pretty_print2(xx)
 "b" => 55
 "a" => 77
 "c" =>
         55 => "beta"
         44 => "alfa"
         66 =>
                "x" => 999
                "y" => 888

也许不是很一般和高效,但你明白了。

编辑:我忘了打印子键的键。我会留给读者来调整这方面的功能。

EDIT2:根据请求,我调整了原始版本以打印子区域的键并添加了一个(可能更漂亮的版本)逐级输出。