Convert type to dictionary

Is there a way to convert a type into a Dict?
Or is there a way to get a list of keys inside a type?

fieldnames(type) will return a Vector{Symbol}

1 Like

I think what you are looking for would be

typedict(x) = Dict(fn=>getfield(x, fn) for fn ∈ fieldnames(x)) 

(in case you were not aware of getfield).

3 Likes

Perfect thanks! Yes getfield doesn’t appear here: https://docs.julialang.org/en/stable/manual/types/

For stuff like that you want to look in the standard library documentation here.

By the way, for what it’s worth, I recommend you avoid doing this if possible. In the general case you will have a Dict{Symbol,Any} so the compiler will no longer know the types of the fields. If you simply leave your struct intact, you won’t have this problem.

1 Like

Thanks for the link. I’ll just use it for pretty printing

Came across this, and just wanted to correct it slightly to:

typedict(x::T) where {T} = Dict(fn=>getfield(x, fn) for fn ∈ fieldnames(T))
3 Likes

:+1:

For a struct the syntax now requires a wrap with typeof(x):

typedict(x) = Dict(fn=>getfield(x, fn) for fn ∈ fieldnames(typeof(x)))

To preserve the order of the fields, you could use OrderedDict instead of Dict or, for small structs, LittleDict is faster and preserves order (both are from OrderedCollections) .

1 Like