How to use DefaultDict in Julia
Overview
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.
Example
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);
Explanation
- Line 4: We create a new
DefaultDictobject with the namedd. We configure 10 as the default value. - Lines 6–9: We'll add four key-value pairs to the
ddobject. - Line 13: We'll access the value for the key
aof theddobject. There is a value associated with the key"a". Hence, that value is returned. - Line 14: We'll access the value for the key
"e"of theddobject. There is no value associated with the key"e". Hence, a new key-value pair"e" - 10is added to theddobject and the new value is returned.
Note: The complete reference to the
DefaultDiccan be found on the official Julia page here.