Otera.Dict (otera v0.1.0)

Copy Markdown View Source

A dictionary that keeps the insertion order of its keys, like a Python dict.

Templates see every map as a dict. The key order matters when a template iterates over a dict or prints it with tojson. Elixir maps do not keep the insertion order, so Otera gives the keys of a plain map in sorted order. To give the keys in a specific order, pass an Otera.Dict:

Otera.Dict.new([{"role", "user"}, {"content", "Hello"}])

Otera.JSON.decode!/1 decodes JSON objects into Otera.Dict structs, with the key order of the JSON text, like json.loads in Python.

A dict works with the Access syntax, dict["role"], and enumerates its {key, value} pairs in order.

Summary

Functions

Returns {:ok, value} for key, or :error.

Returns the keys in order.

Makes a dict from a list of {key, value} pairs.

Sets key to value. A new key goes to the end.

Returns the values in order.

Types

t()

@type t() :: %Otera.Dict{pairs: [{term(), term()}]}

Functions

fetch(dict, key)

@spec fetch(t(), term()) :: {:ok, term()} | :error

Returns {:ok, value} for key, or :error.

keys(dict)

@spec keys(t()) :: [term()]

Returns the keys in order.

new(pairs)

@spec new([{term(), term()}]) :: t()

Makes a dict from a list of {key, value} pairs.

As in Python, a repeated key keeps its first position and its last value, and the keys 1, 1.0 and true are the same key.

put(dict, key, value)

@spec put(t(), term(), term()) :: t()

Sets key to value. A new key goes to the end.

values(dict)

@spec values(t()) :: [term()]

Returns the values in order.