cairo by example

dictionaries

Cairo has a built-in dictionary type called Felt252Dict which maps keys of type Felt252 to values. The dictionary is generic over the type of the stored values.

You can access the values for a specific key with the [] operator. By default, the value 0 is returned for non-existing keys:

    use dict::Felt252DictTrait;

    fn main() -> felt252 {
        let mut dict_u8 = felt252_dict_new::<u8>();
        let mut dict_felt = felt252_dict_new::<felt252>();
        dict_u8.insert(10, 110);

        let val10 = dict_u8[10]; // 110
        let val11 = dict_felt[11]; // 0
        dict_felt.insert(11, 1024);
        dict_felt[11] // 1024
    }


Try it out!
  1. Install the toolchain:
    • For macOS and Linux, run our script:
    • curl -sL https://raw.githubusercontent.com/lambdaclass/cairo-by-example/main/build/installer.sh | bash -s 2.2.0
    • For Windows and others, please see the official guide
  2. Run the example:
    1. Copy the example into a dictionaries.cairo file and run with:
    2. %!s(<nil>) dictionaries.cairo

prev (arrays) next (structs)