How to use the get!() method of dictionary in Julia

Overview

Julia’s get! method gets the value mapped for the specified key. If there is no mapping for the key, the get! method adds a new entry by associating the key with the default value and returns the default value.

Syntax

get!(collection, key, default)

Arguments

This method takes three arguments:

1.collection: This is the collection in which the value is to be retrieved. In our case, the collection will be Dictionary.

2.key: This is the key for which the value is to be retrieved from Dictionary.

3.default: This is the default value to be updated and returned if there is no mapping for the provided key.

Return value

This method returns the value associated with the given key.

Code

The code below demonstrates the use of the get! method:

# Create a Dictionary
SampleDict = Dict("one"=>1, "two"=>2, "three"=>3);
## getting the element for the key "one"
println(get!(SampleDict, "one", 1))
## getting the element for the key "five"
println(get!(SampleDict, "five", 5))
## print the dictionary
println(SampleDict)

Code explanation

Line2: We create a new Dictionary named SamplDict. SamplDict has three entries— {one-1, two-2, three-3}.

Line 5: We use the get! method to get the value associated with the key one. The value 1 is returned as a result.

Line 8: We used the get! method to get the value associated with the key five. There is no entry with key five, so a new entry "five-5" is added to the SampleDict. The default value (5) is returned as a result. Now SampleDict is {two-2,one-1,three-3,five-5}.

Free Resources