Skip to content

Dict[S @ {...}]

Dictionaries are ordered, mutable key-value mappings. They preserve insertion order and are multi-maps: a single key can have multiple values.

Keys can be any hashable type.

Ordering

Dictionaries preserve insertion order. Iteration yields entries in the order they were inserted.

Multi-Map Semantics

A dict can store multiple values per key. This is primarily relevant when constructing dicts from spreading or using methods with the instance parameter:

  • Construction with duplicate keys preserves all values
  • Plain indexing (d[key]) returns the last value for a key, so a duplicate key overrides the values before it: last wins
  • Plain assignment (d[key] = value) replaces all values for a key
  • insert adds a new value without removing existing ones for that key
  • get and pop accept an instance parameter to access specific values by their position (0-indexed) among values for that key; negative instance indexes count from the end

Inherits from: BaseDict[S]

Implements: MutMap[S], Assign[S]

Constructor

Dict source

Builds a dictionary by spreading one source, as {...source} does.

Spreading an array gives positional items, so an array of pairs is not a mapping: Dict [(:a:, 1)] is {(:a:, 1)}. Adapt pairs with Iter.kv instead:

let d = Dict $ pairs.iter().kv()

The lowercase dict factory instead assigns integer keys to positional arguments and symbol keys to key arguments.

Parameters

NameTypeDescription
source Spread[S]

Methods

(assign)[K] key value

Replaces every value of key.

let d = {name: "Alice"}
d[:age:] = 30

Parameters

NameTypeDescription
key K
value AssignItem[S, K]

clear()

Removes all key-value pairs.

let d = {a: 1, b: 2}
d.clear()
assert_eq $d.len 0

Parameters

NameTypeDescription
self Dict[Clearable[S]] Receiver.

copy() -> Dict[S]

Returns a shallow copy of the dictionary, as BaseDict.copy does.

delete[K] key -> Bool

Indicates whether any values were removed. Removes all values for the key.

Parameters

NameTypeDescription
self Dict[Deletable[S, K]] Receiver.
key K

Example

let d = {a: 1, b: 2}
assert (d.delete :a:)
assert (!(d.delete :missing:))
assert_eq $d.len 1

insert[K] key value

Adds a key-value pair. Does not remove existing values for the same key (multi-map insert).

Parameters

NameTypeDescription
key K the key
value InsertItem[S, K] the value

pop[K, D = Never] key … -> (IndexItem[S, K] | D)

Removes and returns a value for a key.

instance selects one of a repeated key's values by position; negative positions count from the end.

Parameters

NameTypeDescription
self Dict[Deletable[S, K]] Receiver.
key K
instance? Int
:default? D
:else? (() -> D)

Errors

Raises IndexError if the key is missing and there is no default or else.

Example

let d @ Dict[Str, Str] = {}
d.insert "multi" "first"
d.insert "multi" "second"

# Pop first instance (default)
assert_eq (d.pop "multi") "first"

# Pop specific instance
assert_eq (d.pop "multi" 0) "second"