struct
Dict
A container that stores key-value pairs.
The key type and value type must be specified statically, unlike a Python dictionary, which can accept arbitrary key and value types.
The key type must implement the KeyElement
trait, which encompasses
Movable
, Hashable
, and EqualityComparable
. It also includes
CollectionElement
and Copyable
until we have references.
The value type must implement the CollectionElement
trait.
Usage:
from collections import Dict
var d = Dict[String, Int]()
d["a"] = 1
d["b"] = 2
print(len(d)) # prints 2
print(d["a"]) # prints 1
print(d.pop("b")) # prints 2
print(len(d)) # prints 1
Parameters
- K (
KeyElement
): The type of the dictionary key. Must be Hashable and EqualityComparable so we can find the key in the map. - V (
CollectionElement
): The value type of the dictionary. Currently must be CollectionElement.
Aliases
EMPTY = -1
:REMOVED = -2
:
Fields
- size (
Int
): The number of elements currently stored in the dict.
Implemented traits
AnyType
,
Boolable
,
CollectionElement
,
Copyable
,
Movable
,
Sized
Methods
__init__
__init__(inout self: Self, /)
Initialize an empty dictiontary.
__init__(inout self: Self, /, existing: Self)
Copy an existing dictiontary.
Args:
- existing (
Self
): The existing dict.
__copyinit__
__copyinit__(inout self: Self, /, existing: Self)
Copy an existing dictiontary.
Args:
- existing (
Self
): The existing dict.
__moveinit__
__moveinit__(inout self: Self, /, owned existing: Self)
Move data of an existing dict into a new one.
Args:
- existing (
Self
): The existing dict.
__bool__
__bool__(self: Self) -> Bool
Check if the dictionary is empty or not.
Returns:
False
if the dictionary is empty, True
if there is at least one element.
__getitem__
__getitem__(self: Self, key: K) -> V
Retrieve a value out of the dictionary.
Args:
- key (
K
): The key to retrieve.
Returns:
The value associated with the key, if it's present.
Raises:
"KeyError" if the key isn't present.
__setitem__
__setitem__(inout self: Self, key: K, value: V)
Set a value in the dictionary by key.
Args:
- key (
K
): The key to associate with the specified value. - value (
V
): The data to store in the dictionary.
__contains__
__contains__(self: Self, key: K) -> Bool
Check if a given key is in the dictionary or not.
Args:
- key (
K
): The key to check.
Returns:
True if there key exists in the dictionary, False otherwise.
__len__
__len__(self: Self) -> Int
The number of elements currenly stored in the dictionary.
__str__
static __str__[T: StringableKeyElement, U: StringableCollectionElement](self: Dict[T, U]) -> String
Returns a string representation of a Dict
.
Note that since we can't condition methods on a trait yet, the way to call this method is a bit special. Here is an example below:
var my_dict = Dict[Int, Float64]()
my_dict[1] = 1.1
my_dict[2] = 2.2
dict_as_string = __type_of(my_dict).__str__(my_dict)
print(dict_as_string)
# prints "{1: 1.1, 2: 2.2}"
When the compiler supports conditional methods, then a simple str(my_dict)
will
be enough.
Parameters:
- T (
StringableKeyElement
): The type of the keys in the Dict. Must implement the traitsStringable
andKeyElement
. - U (
StringableCollectionElement
): The type of the values in the Dict. Must implement the traitsStringable
andCollectionElement
.
Args:
- self (
Dict[T, U]
): The Dict to represent as a string.
Returns:
A string representation of the Dict.
find
find(self: Self, key: K) -> Optional[V]
Find a value in the dictionary by key.
Args:
- key (
K
): The key to search for in the dictionary.
Returns:
An optional value containing a copy of the value if it was present, otherwise an empty Optional.
pop
pop(inout self: Self, key: K, owned default: Optional[V] = #kgen.none) -> V
Remove a value from the dictionary by key.
Args:
- key (
K
): The key to remove from the dictionary. - default (
Optional[V]
): Optionally provide a default value to return if the key was not found instead of raising.
Returns:
The value associated with the key, if it was in the dictionary. If it wasn't, return the provided default value instead.
Raises:
"KeyError" if the key was not present in the dictionary and no default value was provided.
__iter__
__iter__[mutability: i1, self_life: lifetime<*(0,0)>](self: !lit.ref<_stdlib::_collections::_dict::_Dict<:trait<_stdlib::_collections::_dict::_KeyElement> K, :trait<_stdlib::_builtin::_value::_CollectionElement> V>, mut=mutability, self_life>) -> _DictKeyIter[K, V, $0, $1, true]
Iterate over the dict's keys as immutable references.
Parameters:
- mutability (
i1
): Whether the dict is mutable. - self_life (
lifetime<*(0,0)>
): The dict's lifetime.
Returns:
An iterator of immutable references to the dictionary keys.
keys
keys[mutability: i1, self_life: lifetime<*(0,0)>](self: !lit.ref<_stdlib::_collections::_dict::_Dict<:trait<_stdlib::_collections::_dict::_KeyElement> K, :trait<_stdlib::_builtin::_value::_CollectionElement> V>, mut=mutability, self_life>) -> _DictKeyIter[K, V, $0, $1, true]
Iterate over the dict's keys as immutable references.
Parameters:
- mutability (
i1
): Whether the dict is mutable. - self_life (
lifetime<*(0,0)>
): The dict's lifetime.
Returns:
An iterator of immutable references to the dictionary keys.
values
values[mutability: i1, self_life: lifetime<*(0,0)>](self: !lit.ref<_stdlib::_collections::_dict::_Dict<:trait<_stdlib::_collections::_dict::_KeyElement> K, :trait<_stdlib::_builtin::_value::_CollectionElement> V>, mut=mutability, self_life>) -> _DictValueIter[K, V, $0, $1]
Iterate over the dict's values as references.
Parameters:
- mutability (
i1
): Whether the dict is mutable. - self_life (
lifetime<*(0,0)>
): The dict's lifetime.
Returns:
An iterator of references to the dictionary values.
items
items[mutability: i1, self_life: lifetime<*(0,0)>](self: !lit.ref<_stdlib::_collections::_dict::_Dict<:trait<_stdlib::_collections::_dict::_KeyElement> K, :trait<_stdlib::_builtin::_value::_CollectionElement> V>, mut=mutability, self_life>) -> _DictEntryIter[K, V, $0, $1, true]
Iterate over the dict's entries as immutable references.
These can't yet be unpacked like Python dict items, but you can access the key and value as attributes ie.
for e in dict.items():
print(e[].key, e[].value)
Parameters:
- mutability (
i1
): Whether the dict is mutable. - self_life (
lifetime<*(0,0)>
): The dict's lifetime.
Returns:
An iterator of immutable references to the dictionary entries.
update
update(inout self: Self, other: Self, /)
Update the dictionary with the key/value pairs from other, overwriting existing keys. The argument must be positional only.
Args:
- other (
Self
): The dictionary to update from.
__reversed__
__reversed__[mutability: i1, self_life: lifetime<*(0,0)>](self: !lit.ref<_stdlib::_collections::_dict::_Dict<:trait<_stdlib::_collections::_dict::_KeyElement> K, :trait<_stdlib::_builtin::_value::_CollectionElement> V>, mut=mutability, self_life>) -> _DictKeyIter[K, V, $0, $1, false]
Iterate backwards over the dict keys, returning immutable references.
Returns:
A reversed iterator of immutable references to the dict keys.