Julia Struct to Dict

Viewed 487

can anybody help me. I just want to convert a Struct/Typ to a Dict in Julia.

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

I need to convert an object from "S" to a dict.

2 Answers

Suppose you have an object s:

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

You can convert it to a Dict as:

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

Note that Dicts have non fixed ordering. If you need to keep the same field order you could use OrderedDict from OrderedCollections.

You can also use comprehension (this actually looks to be 30% faster):

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))

If s is an instance of S, then you can also use:

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

The difference is that you don't need to use the type name S.

Note: fieldnames(typeof(s)) is slower than propertynames(s)!

Related