Thursday, 12 December 2013

Dictionaries in Julia

I always seem to forget how to use dictionaries in Julia, so I thought I'd cover some of the common use cases here.


Create an empty dictionary:

dict = Dict()
dict["a"] = 1
dict["b"] = 2

The above Dict is of type Dict{Any,Any}, so anything can be used for keys or values. To create an empty dictionary that explicitly maps strings to floats:

d = Dict{String,Float32}()
d["q"] = 3 # works
d[32] = 3 # fails, expected a string key

Create a pre-filled Dict (note the different brace styles):

# infers type information Dict{ASCIIString,Int64} 
# created in this case
dict = ["Jan"=> 1, "Feb"=> 2, "Mar"=> 3] 
# -or-
# creates dict of type Dict{Any,Any}
dict = {"Jan"=> 1, "Feb"=> 2, "Mar"=> 3} 

Iterate over the keys of a Dict:

for key = keys(dict)
    println("$key: $(dict[key])")
# values(dict) works the same way to extract values

Getting values from a dictionary:

# raises an error if "Dec" is not present
temp = dict["Dec"]   
# returns a default value (0 in this case) 
# if "Dec" is not present.
temp = get(dict,"Dec",0)  

Instead of the get() function above, haskey(dict,key) can also be used to check if a key is present. Full documentation is here.

1 comment:

  1. Hi James
    Is it possible to make a dict relatinha the string with more than 1 values?
    d["q"] = 3 5

    I have a file with 3 columns and my idea is to make a dict relating the first with the others ( col1 => col2 col3).
    Any suggestion ?

    Thank you!