In Julia, DefaultDict
is a type of DefaultDict
, it allows us to return a default value instead of raising a KeyError
.
If we try to access the value for a key that is not present inside the DefaultDict
object, the DefaultDict
will insert a new key-value pair with the given key and default value configured to the DefaultDict
object. DefaultDict
will then return this newly created value.
Below is a sample code for using the DefaultDict
in Julia:
using DataStructures# Create a new DefaultDict object which will return 10 as default valuedd = DefaultDict(10)dd["a"] = 1;dd["b"] = 2;dd["c"] = 3;dd["d"] = 4;println(dd);println("dd['a'] :", dd["a"]);println("dd['e'] :", dd["e"]);println(dd);
DefaultDict
object with the name dd
. We configure 10 as the default value.dd
object.a
of the dd
object. There is a value associated with the key "a"
. Hence, that value is returned."e"
of the dd
object. There is no value associated with the key "e"
. Hence, a new key-value pair "e" - 10
is added to the dd
object and the new value is returned.Note: The complete reference to the
DefaultDic
can be found on the official Julia page here.