Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

defaultdict
julia
data structures
communitycreator

How to use DefaultDict in Julia

Programming Bytes

Overview

In Julia, DefaultDict is a type of DictionaryA collection of key-value pairs, where each value is associated with a unique key.. The only difference is that when the requested key is not present inside the 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 value 
dd = 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);
Using the DefaultDict

Explanation

  • Line 4: We create a new DefaultDict object with the name dd. We configure 10 as the default value.
  • Lines 6–9: We'll add four key-value pairs to the dd object.
  • Line 13: We'll access the value for the key a of the dd object. 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 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.

RELATED TAGS

defaultdict
julia
data structures
communitycreator
RELATED COURSES

View all Courses

Keep Exploring