Mojo 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
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
,
CollectionElementNew
,
Copyable
,
ExplicitlyCopyable
,
Movable
,
Sized
Methodsβ
__init__
β
__init__(inout self: Self)
Initialize an empty dictiontary.
__init__(inout self: Self, *, power_of_two_initial_capacity: Int)
Initialize an empty dictiontary with a pre-reserved initial capacity.
Example usage:
var x = Dict[Int,Int](power_of_two_initial_capacity = 1024)
# Insert (2/3 of 1024) entries without reallocation.
var x = Dict[Int,Int](power_of_two_initial_capacity = 1024)
# Insert (2/3 of 1024) entries without reallocation.
Args:
- βpower_of_two_initial_capacity (
Int
): At least 8, has to be a power of two.
__init__(inout self: Self, *, other: Self)
Copy an existing dictiontary.
Args:
- βother (
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, owned key: K, owned 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.
__or__
β
__or__(self: Self, other: Self) -> Self
Merge self with other and return the result as a new dict.
Args:
- βother (
Self
): The dictionary to merge with.
Returns:
The result of the merge.
__ior__
β
__ior__(inout self: Self, other: Self)
Merge self with other in place.
Args:
- βother (
Self
): The dictionary to merge with.
fromkeys
β
static fromkeys(keys: List[K, hint_trivial_type], value: V) -> Self
Create a new dictionary with keys from list and values set to value.
Args:
- βkeys (
List[K, hint_trivial_type]
): The keys to set. - βvalue (
V
): The value to set.
Returns:
The new dictionary.
static fromkeys(keys: List[K, hint_trivial_type], value: Optional[V] = #kgen.none) -> Dict[K, Optional[V]]
Create a new dictionary with keys from list and values set to value.
Args:
- βkeys (
List[K, hint_trivial_type]
): The keys to set. - βvalue (
Optional[V]
): The value to set.
Returns:
The new dictionary.
__iter__
β
__iter__(ref [self_is_lifetime] self: Self) -> _DictKeyIter[$0, K, V, $1, 1]
Iterate over the dict's keys as immutable references.
Returns:
An iterator of immutable references to the dictionary keys.
__reversed__
β
__reversed__(ref [self_is_lifetime] self: Self) -> _DictKeyIter[$0, K, V, $1, 0]
Iterate backwards over the dict keys, returning immutable references.
Returns:
A reversed iterator of immutable references to the dict keys.
__len__
β
__len__(self: Self) -> Int
The number of elements currently stored in the dictionary.
Returns:
The number of elements currently stored in the dictionary.
__str__
β
__str__[T: RepresentableKeyElement, U: RepresentableCollectionElement, //](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 = my_dict.__str__()
print(dict_as_string)
# prints "{1: 1.1, 2: 2.2}"
var my_dict = Dict[Int, Float64]()
my_dict[1] = 1.1
my_dict[2] = 2.2
dict_as_string = my_dict.__str__()
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.
Note that both they keys and values' types must implement the __repr__()
method
for this to work. See the Representable
trait for more information.
Parameters:
- βT (
RepresentableKeyElement
): The type of the keys in the Dict. Must implement the traitsRepresentable
andKeyElement
. - βU (
RepresentableCollectionElement
): The type of the values in the Dict. Must implement the traitsRepresentable
andCollectionElement
.
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.
get
β
get(self: Self, key: K) -> Optional[V]
Get a value from 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.
get(self: Self, key: K, default: V) -> V
Get a value from the dictionary by key.
Args:
- βkey (
K
): The key to search for in the dictionary. - βdefault (
V
): Default value to return.
Returns:
A copy of the value if it was present, otherwise default.
pop
β
pop(inout self: Self, key: K, owned default: V) -> V
Remove a value from the dictionary by key.
Args:
- βkey (
K
): The key to remove from the dictionary. - βdefault (
V
): 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.
pop(inout self: Self, key: K) -> V
Remove a value from the dictionary by key.
Args:
- βkey (
K
): The key to remove from the dictionary.
Returns:
The value associated with the key, if it was in the dictionary. Raises otherwise.
Raises:
"KeyError" if the key was not present in the dictionary.
popitem
β
popitem(inout self: Self) -> DictEntry[K, V]
Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order. popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError.
Args: None
Returns:
Last dictionary item
Raises:
"KeyError" if the dictionary is empty.
keys
β
keys(ref [self_is_lifetime] self: Self) -> _DictKeyIter[$0, K, V, $1, 1]
Iterate over the dict's keys as immutable references.
Returns:
An iterator of immutable references to the dictionary keys.
values
β
values(ref [self_is_lifetime] self: Self) -> _DictValueIter[$0, K, V, $1, 1]
Iterate over the dict's values as references.
Returns:
An iterator of references to the dictionary values.
items
β
items(ref [self_is_lifetime] self: Self) -> _DictEntryIter[$0, K, V, $1, 1]
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)
for e in dict.items():
print(e[].key, e[].value)
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.
clear
β
clear(inout self: Self)
Remove all elements from the dictionary.
setdefault
β
setdefault(inout self: Self, key: K, owned default: V) -> Reference[1, V, *[0,0], 0]
Get a value from the dictionary by key, or set it to a default if it doesn't exist.
Args:
- βkey (
K
): The key to search for in the dictionary. - βdefault (
V
): The default value to set if the key is not present.
Returns:
The value associated with the key, or the default value if it wasn't present.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!
π What went wrong?