Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to save and retrieve dictionaries in Julia?

I have seen that Julia adequately interprets "MAT" files which have structures in them which are read as dictionaries without problem. Now I have created a dictionary of my own, which has the following structure

(String, String)=> [ Int, Int, Int]

on each entry. I can save it with writedlm and it produces a very orderly tabular text file, separated by tabs (\t), but then I cannot retrieve it without doing a LOT of parsing. If I use readdlm I get an array of type Any, with the very uncomfortable structure at each line

"(\"Bla bla\", \"tururu\")"     "[a, b, c]"

That is, two columns of Strings which contain signs such as '"' and '['.

like image 641
wpkzz Avatar asked Jun 23 '15 21:06

wpkzz


People also ask

How do you access the dictionary in Julia?

A dictionary in Julia can be created with a pre-defined keyword Dict(). This keyword accepts key-value pairs as arguments and generates a dictionary by defining its data type based on the data type of the key-value pairs. One can also pre-define the data type of the dictionary if the data type of the values is known.

Are Dictionaries mutable in Julia?

The values of Dictionary are mutable, or "settable", and can be modified via setindex! . However, just like for Array s, new indices (keys) are never created or rearranged this way.

Are Dictionaries slow in Julia?

You could write a caching wrapper. Compared to python, dictionary lookup is very fast. This is ridiculously slow, because it involves a non-inlined runtime call to jl_object_id . At some point in the future it will probably get faster (someone writes an if @generated fallback that treats objects as blobs of memory).


2 Answers

You could use the JLD (Julia Data) submodule included in the HDF5 package:

Pkg.add("HDF5")
using HDF5, JLD
d = Dict(
    ("a", "b") => [1, 2, 3],
    ("c", "d") => [4, 5, 6],
    ("e", "f") => [7, 8, 9]
)
save("data.jld", "data", d)
load("data.jld")["data"]

the advantage of the JLD module is that it preserves the exact type information of each variable.

like image 110
HarmonicaMuse Avatar answered Oct 20 '22 11:10

HarmonicaMuse


The solution using JLD suggested by SalchiPapa no longer works for some reason. Here is an updated version (just changed the imports and the file extension) of their example using JLD2:

using JLD2, FileIO
d = Dict(
        ("a", "b") => [1, 2, 3],
        ("c", "d") => [4, 5, 6],
        ("e", "f") => [7, 8, 9]
    )
save("data.jld2", "data", d)
load("data.jld2")["data"]
like image 28
leohallier Avatar answered Oct 20 '22 09:10

leohallier