Cadence Data Strucuture: Dictionary Deep Dive

Dictionaries

Dictionary literals start with an opening brace { and end with a closing brace }. Keys are separated from values by a colon, and key-value associations are separated by commas.

1. Types

Dictionary types have the form {K: V}, where K is the type of the key, and V is the type of the value. For example, a dictionary with Int keys and Bool values has type {Int: Bool}.

In a dictionary, all keys must have a type that is a subtype of the dictionary's key type (K) and all values must have a type that is a subtype of the dictionary's value type (V).

Declare a constant that has type {Int: Bool},

let integers = {

true: 1,

false: 0

}

2. Access

To get the value for a specific key from a dictionary, the access syntax can be used: The dictionary is followed by an opening square bracket [, the key, and ends with a closing square bracket ].

Declare a constant that has type {Int: Bool},

let integers = {

true: 1,

false: 0

}

integers[true] // is 1

integers[false] // is 0

integers[false] = 9 // is now 9

3. Fields and Functions

Examples of functions of a dictionary

let numbers = {"fortyTwo": 42, "twentyThree": 23}

numbers.length // 2

numbers.insert(key: "fortyTwo", 42)

numbers.remove(key: "fortyTwo") // 42 popped

numbers.values // numbers is now [42, 23]