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.
Examples:
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__(out self)
Initialize an empty dictiontary.
__init__(out self, *, power_of_two_initial_capacity: Int)
Initialize an empty dictiontary with a pre-reserved initial capacity.
Example usage:
from collections import Dict
var x = Dict[Int, Int](power_of_two_initial_capacity = 1024)
# Insert (2/3 of 1024) entries without reallocation.
from collections import Dict
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__(out self, *, other: Self)
Copy an existing dictiontary.
Args:
- other (
Self
): The existing dict.
__copyinit__
__copyinit__(out self, existing: Self)
Copy an existing dictiontary.
Args:
- existing (
Self
): The existing dict.
__moveinit__
__moveinit__(out self, owned existing: Self)
Move data of an existing dict into a new one.
Args:
- existing (
Self
): The existing dict.
__bool__
__bool__(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, key: K) -> ref [*[0,0]._entries._value.value] 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, 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, 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, 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, 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] = Optional(#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) -> _DictKeyIter[K, V, self_is_origin]
Iterate over the dict's keys as immutable references.
Returns:
An iterator of immutable references to the dictionary keys.
__reversed__
__reversed__(ref self) -> _DictKeyIter[K, V, self_is_origin, False]
Iterate backwards over the dict keys, returning immutable references.
Returns:
A reversed iterator of immutable references to the dict keys.
__len__
__len__(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:
from collections import Dict
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}"
from collections import Dict
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, 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, 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, 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, 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, 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) -> 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) -> _DictKeyIter[K, V, self_is_origin]
Iterate over the dict's keys as immutable references.
Returns:
An iterator of immutable references to the dictionary keys.
values
values(ref self) -> _DictValueIter[K, V, self_is_origin]
Iterate over the dict's values as references.
Returns:
An iterator of references to the dictionary values.
items
items(ref self) -> _DictEntryIter[K, V, self_is_origin]
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.
from collections import Dict
var my_dict = Dict[String, Int]()
my_dict["a"] = 1
my_dict["b"] = 2
for e in my_dict.items():
print(e[].key, e[].value)
from collections import Dict
var my_dict = Dict[String, Int]()
my_dict["a"] = 1
my_dict["b"] = 2
for e in my_dict.items():
print(e[].key, e[].value)
Returns:
An iterator of immutable references to the dictionary entries.
update
update(inout 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)
Remove all elements from the dictionary.
setdefault
setdefault(inout self, key: K, owned default: V) -> ref [*[0,0]._entries._value.value] V
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!