Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

conversion to Dict #91

Open
scheidan opened this issue Jun 18, 2020 · 0 comments
Open

conversion to Dict #91

scheidan opened this issue Jun 18, 2020 · 0 comments

Comments

@scheidan
Copy link
Contributor

Hi
I recently was in need to convert a NamedArray in a nested dictionary (for JSON export) and wrote the little (and probably very inefficient) function below. If this functionality is useful of others as well is could be added to the package.

function Dict(na::NamedArray)
    ndim = length(size(na))
    if ndim == 1
        return Dict(names(na)[1][i] => na[i] for i in 1:length(na))
    else
        d = Dict()
        for i in 1:size(na, 1)
            idx = [i; fill(:, ndim-1)]
            d[names(na)[1][i]] = Dict(na[idx...])
        end
        return d
    end
end

Example

na = NamedArray(rand(3))
setnames!(na, ["sub_$i" for i in 1:3], 1)
setnames!(na, ["loss_$i" for i in 1:4], 2)
setnames!(na, ["tech_$i" for i in 1:5], 3)
nd = Dict(na)

na["sub_1", "loss_3", "tech_2"]
nd["sub_1"]["loss_3"]["tech_2"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant