Convert type to dictionary


#1

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?


#2

fieldnames(type) will return a Vector{Symbol}


#3

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


#4

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


#5

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.


#6

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