Julia 结构转字典

Julia Struct to Dict

谁能帮帮我。我只想将 Struct/Typ 转换为 Julia 中的字典。

  struct A
    A1::Int
    A2::Int
end
struct S
    atrr1::String
    attr2::String
    attr3::Int
    attr4::A
end

我需要将对象从“S”转换为字典。

假设你有一个对象s:

julia> s = S("a","b",3,A(4,5))
S("a", "b", 3, A(4, 5))

您可以将其转换为 Dict 为:

julia> Dict(fieldnames(S) .=> getfield.(Ref(s), fieldnames(S)))
Dict{Symbol, Any} with 4 entries:
  :attr2 => "b"
  :attr4 => A(4, 5)
  :atrr1 => "a"
  :attr3 => 3

请注意 Dict 的顺序不固定。如果您需要保持相同的字段顺序,您可以使用 OrderedCollections.

中的 OrderedDict

你也可以使用理解(这实际上看起来快了 30%):

julia> Dict(key=>getfield(s, key) for key ∈ fieldnames(S))
Dict{Symbol, Any} with 4 entries:
  :attr2 => "b"
  :attr4 => A(4, 5)
  :atrr1 => "a"
  :attr3 => 3
julia> Dict(key=>getfield(s, key) for key ∈ fieldnames(S))

如果s是S的一个实例,那么你也可以使用:

function struct_to_dict(s)
  return Dict(key => getfield(s, key) for key in propertynames(s))
end

不同之处在于您不需要使用类型名称 S。

注意:fieldnames(typeof(s))propertynames(s) 慢!