Dictionaries in Julia - Beginner's tutorial [with examples]

Written by Administrator on Sunday May 10, 2020

Dictionary is a kind of Data Structure in many programming languages and it is a part of Julia programming language as well. Let's create a simple example for understand, how Dictionaries work in Julia.

Imagine we have a Car Store and we're selling different cars. Our plan is to create a list of cars with possibility of looking for a price by giving a car's name.

Creating a Dictionary

Creating Dict variable, which will represent our pricelist. As a key we will store the name of a product and as a value we will store its price (let's say in US Dollars):

julia> Pricelist = Dict("Honda" => 12000, "Fiat" => 9800, "Ford" => 11000, "Lambo" => 175000)

You see, the core of a Dictionary is a pair of two values. In our case a name of a car is a key and car's price is a value.

There're a lot things we can do with Dict in Julia. Let's test, what all we can do with it:


List keys and values in Dictionary in Julia

As you remember, car's names are keys in our dictionary and prices are values. So, in case your need a list of all cars in your price list, you are listing keys:

julia> keys(Pricelist)

and we will see a list of all cars we sell:

  "Fiat"
  "Ford"
  "Lamborghini"
  "Honda"

In case you need a list of all prices, we will use values:

julia> values(Pricelist)

result:

  9800
  11000
  175000
  12000

Searching in Dictionary

We can use our Pricelist to search in it. In case our Pricelist is very big, we surely cannot remember all prices, but we don't have to, we can search a price by entering the name of car. This request:

julia> Pricelist["Fiat"]

will result in:

11000

The same way we can look for a price of any car:

julia> Pricelist["Fiat"]
9800

Catching a mistake

But what will happen, when we try to find a price of car, that we don't have? This situation can easily happe, because our Pricelist can be very long and nobody can memorize it. Let's see:

julia> Pricelist["Toyota"]

and output:

ERROR: KeyError: key "Toyota" not found
Stacktrace:
 [1] getindex(::Dict{String,Int64}, ::String) at ./dict.jl:478
 [2] top-level scope at none:0

Ooops, key "Toyota" not found. Surely it wasn't, because we don't sell "Toyotas" (for now ;). In this case we have something to do with this situation (at least put an alert and give a user an information, that this car is not listed in Pricelist or something like that).


Creating a simple function in Julia

To solve this problem, we will create a function GetPrice, which will have more complex functionality:

function GetPrice(car_name)
    if haskey(Pricelist,car_name)
        return Pricelist[car_name]
    else
        println("This car is not in Price list")
    end
end

Our function GetPrice checks, if car name we provide (as argument for this function) exists in our Pricelist. In case yes, it will find the price of a car and return us the price. In case provided car's name is not in our Pricelist, it will write notification for us ("This car is not in Price list").

Let's test, how it works. If you run following command:

julia> GetPrice("Ford")

you will receive this:

11000

But if we ask for a price, which is not in our Pricelist:

julia> GetPrice("Toyota")

program will return us this:

This car is not in Price list

Now we can be calm in case of requesting a price of non-existing car.


Search a maximum value in Dictionary in Julia

Ok, our Pricelist can provide us car's price by it's name. What if we want to know the most expensive var in our pricelist (meaning, how to find the biggest value in Dictionary). It's very simple. We just call:

julia> maximum(Pricelist)

and we will know, that this is:

julia> "Lamborghini" => 175000

Search a maximum value in Dictionary in Julia

In case of searching the cheapest car (meaning, the smallest value in Dictionary) is very similar (we will use minimum instead of maximum). Let's find the cheapest car:

julia> minimum(Pricelist)
"Fiat" => 9800

Merging two dictionaries in Julia

Now imagine we are expanding and want to sell more cars of different manufacturers. You started to sell "Toyota" and "Aston Martin" cars and you issued new pricelist:

Pricelist2 = Dict("Toyota"=>18000, "Aston Martin" => 220000)

You aim is use both price lists, but it's difficult to operate with two of them. Sure, it's good idea to make one big Price list (meaning merge two Dictionaries). It's important to keep in mind, that merging two Dicts in Julia (as well as in other programming languages) is possible only in case they have the same structure. That's why our Pricelist2 has the same structure as previous Pricelist.

So, let's create a new price list, which will combine Pricelist and Pricelist2:

julia> NewPricelist = merge(Pricelist,Pricelist2)

Now we have NewPricelist:

NewPricelist = merge(Pricelist,Pricelist2)
Dict{String,Int64} with 6 entries:
  "Fiat"          => 9800
  "Ford"          => 11000
  "Lamborghini"   => 175000
  "Toyota"        => 18000
  "Aston Martin" => 220000
  "Honda"         => 12000

Adding an item to a Dictionary in Julia

Now let's imagine we are going to sell a new type of car (Volvo). So, we have to add new record (in our case Pair (car-price) in an existing Dictionary (it's NewPricelist in our case):

push!(NewPriceslist, "Volvo" => 45000)

Category: julia Tags: julia Dict