Documentation¶
Sorted Dictionary¶
- class pysorteddict.SortedDict¶
Sorted analogue of the
dicttype. Wraps the C++ sorted dictionary (std::map): key-value pairs are stored in ascending order of the keys, which must all be of the same type.The following key types are always supported.
boolbytesfloatintstr
The following key types are supported if they are importable (which they should always be—failure to import them may be a sign of a corrupt or damaged Python installation).
datetime.datedatetime.timedeltadecimal.Decimalfractions.Fractionipaddress.IPv4Addressipaddress.IPv4Interfaceipaddress.IPv4Networkipaddress.IPv6Addressipaddress.IPv6Interfaceipaddress.IPv6Networkpathlib.PosixPathpathlib.PurePosixPathpathlib.PureWindowsPathpathlib.WindowsPathtime.struct_timeuuid.UUID
Shadowing standard library modules providing these types may lead to undefined behaviour.
from pathlib import Path with Path(__file__).with_name("decimal.py").open("w") as writer: print("import math", file=writer) print('Decimal = type("Decimal", (float,), {"is_nan": lambda self: math.isnan(self)})', file=writer) from pysorteddict import SortedDict from decimal import Decimal d = SortedDict() d[Decimal(0)] = None
Here, the imported
Decimal(which is actuallyfloatwith anis_nanmethod defined) came from the newly createddecimal.pyinstead of the standard library moduledecimal. This will work. However, ifDecimal.__lt__(the comparison function used by the underlying C++std::map) is overridden to raise an exception, undefined behaviour will result.The methods of
SortedDictare somewhat similar to those ofdict.- __init__()¶
Initialise an empty sorted dictionary.
- property key_type: type | None¶
The key type of the sorted dictionary, or
Noneif no key-value pairs have been inserted yet.from pysorteddict import SortedDict d = SortedDict() assert d.key_type is None d[b"foo"] = () assert d.key_type is bytes
- __repr__() str¶
Return a human-readable representation of the sorted dictionary.
- __contains__(key: Any) bool¶
Return whether
keyis present in the sorted dictionary.This method may raise exceptions.
- Raises:
RuntimeError – if no key-value pairs have been inserted yet.
from pysorteddict import SortedDict d = SortedDict() "foo" in d
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) Cell In[2], line 4 1 from pysorteddict import SortedDict 3 d = SortedDict() ----> 4 "foo" in d RuntimeError: key type not set: insert at least one item first
- Raises:
TypeError – if
type(key)does not match the type of the first key inserted.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = ("bar", "baz") 100 in d
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[3], line 5 3 d = SortedDict() 4 d["foo"] = ("bar", "baz") ----> 5 100 in d TypeError: got key 100 of type <class 'int'>, want key of type <class 'str'>
- Raises:
ValueError – if
keyis not comparable with instances of its type.
from pysorteddict import SortedDict d = SortedDict() d[1.1] = ("racecar",) float("nan") in d
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[4], line 5 3 d = SortedDict() 4 d[1.1] = ("racecar",) ----> 5 float("nan") in d ValueError: got bad key nan of type <class 'float'>
- __len__() int¶
Return the number of key-value pairs in the sorted dictionary.
This method may raise exceptions.
- Raises:
OverflowError – if the number of key-value pairs exceeds
PY_SSIZE_T_MAX(which is usually 9223372036854775807 on 64-bit operating systems, making this exception astronomically unlikely).
- __getitem__(key: Any) Any¶
Return the value mapped to
keyin the sorted dictionary.This method may raise exceptions.
- Raises:
RuntimeError – if no key-value pairs have been inserted yet.
from pysorteddict import SortedDict d = SortedDict() d["foo"]
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) Cell In[5], line 4 1 from pysorteddict import SortedDict 3 d = SortedDict() ----> 4 d["foo"] RuntimeError: key type not set: insert at least one item first
- Raises:
TypeError – if
type(key)does not match the type of the first key inserted.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = ("bar", "baz") d[100]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[6], line 5 3 d = SortedDict() 4 d["foo"] = ("bar", "baz") ----> 5 d[100] TypeError: got key 100 of type <class 'int'>, want key of type <class 'str'>
- Raises:
ValueError – if
keyis not comparable with instances of its type.
from pysorteddict import SortedDict d = SortedDict() d[1.1] = ("racecar",) d[float("nan")]
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[7], line 5 3 d = SortedDict() 4 d[1.1] = ("racecar",) ----> 5 d[float("nan")] ValueError: got bad key nan of type <class 'float'>
- Raises:
KeyError – if
keyis not present in the sorted dictionary.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = ("bar", "baz") d["spam"]
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[8], line 5 3 d = SortedDict() 4 d["foo"] = ("bar", "baz") ----> 5 d["spam"] KeyError: 'spam'
- __setitem__(key: Any, value: Any)¶
Insert
keyinto the sorted dictionary (if it isn’t already in it) and mapvalueto it, replacing the previously mapped value (if any).This method may raise exceptions.
- Raises:
TypeError – if no key-value pairs have been inserted yet and
type(key)isn’t one of the supported types.
from pysorteddict import SortedDict d = SortedDict() d[["eggs"]] = None
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[9], line 4 1 from pysorteddict import SortedDict 3 d = SortedDict() ----> 4 d[["eggs"]] = None TypeError: got key ['eggs'] of unsupported type <class 'list'>
- Raises:
TypeError – if
type(key)does not match the type of the first key inserted.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = ("bar", "baz") d[100] = "spam"
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[10], line 5 3 d = SortedDict() 4 d["foo"] = ("bar", "baz") ----> 5 d[100] = "spam" TypeError: got key 100 of type <class 'int'>, want key of type <class 'str'>
- Raises:
ValueError – if
keyis not comparable with instances of its type.
from pysorteddict import SortedDict d = SortedDict() d[1.1] = ("racecar",) d[float("nan")] = {}
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[11], line 5 3 d = SortedDict() 4 d[1.1] = ("racecar",) ----> 5 d[float("nan")] = {} ValueError: got bad key nan of type <class 'float'>
- __delitem__(key: Any)¶
Remove
keyand the value mapped to it from the sorted dictionary.This method may raise exceptions.
- Raises:
RuntimeError – if no key-value pairs have been inserted yet.
from pysorteddict import SortedDict d = SortedDict() del d["foo"]
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) Cell In[12], line 4 1 from pysorteddict import SortedDict 3 d = SortedDict() ----> 4 del d["foo"] RuntimeError: key type not set: insert at least one item first
- Raises:
TypeError – if
type(key)does not match the type of the first key inserted.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = ("bar", "baz") del d[100]
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[13], line 5 3 d = SortedDict() 4 d["foo"] = ("bar", "baz") ----> 5 del d[100] TypeError: got key 100 of type <class 'int'>, want key of type <class 'str'>
- Raises:
ValueError – if
keyis not comparable with instances of its type.
from pysorteddict import SortedDict d = SortedDict() d[1.1] = ("racecar",) del d[float("nan")]
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[14], line 5 3 d = SortedDict() 4 d[1.1] = ("racecar",) ----> 5 del d[float("nan")] ValueError: got bad key nan of type <class 'float'>
- Raises:
KeyError – if
keyis not present in the sorted dictionary.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = ("bar", "baz") del d["spam"]
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[15], line 5 3 d = SortedDict() 4 d["foo"] = ("bar", "baz") ----> 5 del d["spam"] KeyError: 'spam'
- Raises:
RuntimeError – if there exists a forward iterator over the items, keys or values of the sorted dictionary pointing to
key(meaning that callingnexton the iterator would return(key, d[key]),keyord[key]respectively).
from pysorteddict import SortedDict d = SortedDict() for i in range(5): d[i] = None ii = iter(d.items()) ki = iter(d.keys()) vi = iter(d.values()) del d[0]
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) Cell In[16], line 9 7 ki = iter(d.keys()) 8 vi = iter(d.values()) ----> 9 del d[0] RuntimeError: operation not permitted: key-value pair locked by 3 iterator(s)
- Raises:
RuntimeError – if there exists a reverse iterator over the items, keys or values of the sorted dictionary pointing to the key immediately less than
key(meaning that callingnexton the iterator last returned(key, d[key]),keyord[key]respectively).
from pysorteddict import SortedDict d = SortedDict() for i in range(5): d[i] = None ii = reversed(d.items()) ki = reversed(d.keys()) vi = reversed(d.values()) assert (next(ii), next(ki), next(vi)) == ((4, None), 4, None) del d[4]
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) Cell In[17], line 10 8 vi = reversed(d.values()) 9 assert (next(ii), next(ki), next(vi)) == ((4, None), 4, None) ---> 10 del d[4] RuntimeError: operation not permitted: key-value pair locked by 3 iterator(s)
This method may behave differently with PyPy.
PyPy does not run the destructor of an object immediately after it becomes unreachable. Hence, iterators deleted prematurely will keep a key-value pair locked.
import gc from pysorteddict import SortedDict d = SortedDict() d["foo"] = "bar" d["baz"] = 1 ii = iter(d.items()) ki = iter(d.keys()) vi = iter(d.values()) del ii, ki, vi # gc.collect() del d["baz"]
Uncommenting the commented line runs any required destructors, ensuring that no exception is raised.
- __iter__() SortedDictKeysFwdIter¶
Return a forward iterator over the keys in the sorted dictionary.
iter(d)is an efficient shorthand foriter(d.keys()). Typical usage is to iterate directly over the sorted dictionary instead of making this call.from pysorteddict import SortedDict d = SortedDict() d["foo"] = () d["bar"] = [100] d["baz"] = 3.14 for key in d: print(key)
bar baz foo
See also
SortedDictKeys.__iter__().- __reversed__() SortedDictKeysRevIter¶
Return a reverse iterator over the keys in the sorted dictionary.
reversed(d)is an efficient shorthand forreversed(d.keys()).from pysorteddict import SortedDict d = SortedDict() d["foo"] = () d["bar"] = [100] d["baz"] = 3.14 for key in reversed(d): print(key)
foo baz bar
See also
SortedDictKeys.__reversed__().- clear()¶
Remove all key-value pairs in the sorted dictionary.
This method may raise exceptions.
- Raises:
RuntimeError – if there exist unexhausted iterators over the items, keys or values of the sorted dictionary.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = "bar" ii = iter(d.items()) ki = iter(d.keys()) vi = reversed(d.values()) d.clear()
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) Cell In[20], line 8 6 ki = iter(d.keys()) 7 vi = reversed(d.values()) ----> 8 d.clear() RuntimeError: operation not permitted: sorted dictionary locked by 3 iterator(s)
This method may behave differently with PyPy.
PyPy does not run the destructor of an object immediately after it becomes unreachable. Hence, iterators deleted prematurely will keep a sorted dictionary locked.
import gc from pysorteddict import SortedDict d = SortedDict() d["foo"] = "bar" ii = iter(d.items()) ki = iter(d.keys()) vi = reversed(d.values()) del ii, ki, vi # gc.collect() d.clear()
Uncommenting the commented line runs any required destructors, ensuring that no exception is raised.
- copy() SortedDict¶
Return a shallow copy of the sorted dictionary.
- get(key: Any, default: Any = None, /) Any¶
Return the value mapped to
keyin the sorted dictionary, ordefaultifkeyisn’t in present in it.from pysorteddict import SortedDict d = SortedDict() d["foo"] = "bar" assert d.get("foo") == "bar" assert d.get("baz") is None assert d.get("spam", "eggs") == "eggs"
This method may raise exceptions.
- Raises:
RuntimeError – if no key-value pairs have been inserted yet.
from pysorteddict import SortedDict d = SortedDict() d.get("foo")
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) Cell In[22], line 4 1 from pysorteddict import SortedDict 3 d = SortedDict() ----> 4 d.get("foo") RuntimeError: key type not set: insert at least one item first
- Raises:
TypeError – if
type(key)does not match the type of the first key inserted.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = ("bar", "baz") d.get(100)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[23], line 5 3 d = SortedDict() 4 d["foo"] = ("bar", "baz") ----> 5 d.get(100) TypeError: got key 100 of type <class 'int'>, want key of type <class 'str'>
- Raises:
ValueError – if
keyis not comparable with instances of its type.
from pysorteddict import SortedDict d = SortedDict() d[1.1] = ("racecar",) d.get(float("nan"))
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[24], line 5 3 d = SortedDict() 4 d[1.1] = ("racecar",) ----> 5 d.get(float("nan")) ValueError: got bad key nan of type <class 'float'>
- items() SortedDictItems¶
Return a dynamic view on the key-value pairs in the sorted dictionary.
from pysorteddict import SortedDict d = SortedDict() items = d.items() d["foo"] = () print(items) d["bar"] = [100] print(items) d["baz"] = 3.14 print(items)
SortedDictItems([('foo', ())]) SortedDictItems([('bar', [100]), ('foo', ())]) SortedDictItems([('bar', [100]), ('baz', 3.14), ('foo', ())])
- keys() SortedDictKeys¶
Return a dynamic view on the keys in the sorted dictionary.
from pysorteddict import SortedDict d = SortedDict() keys = d.keys() d["foo"] = () print(keys) d["bar"] = [100] print(keys) d["baz"] = 3.14 print(keys)
SortedDictKeys(['foo']) SortedDictKeys(['bar', 'foo']) SortedDictKeys(['bar', 'baz', 'foo'])
- setdefault(key: Any, default: Any = None, /) Any¶
If
keyis present in the sorted dictionary, return the value mapped to it. Otherwise, insertkeyinto it, mapdefaulttokeyand returndefault.from pysorteddict import SortedDict d = SortedDict() d["foo"] = "bar" assert d.setdefault("foo") == "bar" assert d.setdefault("baz") is None assert d["baz"] is None assert d.setdefault("spam", "eggs") == "eggs" assert d["spam"] == "eggs"
This method may raise exceptions.
- Raises:
RuntimeError – if no key-value pairs have been inserted yet.
from pysorteddict import SortedDict d = SortedDict() d.setdefault("foo")
--------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) Cell In[28], line 4 1 from pysorteddict import SortedDict 3 d = SortedDict() ----> 4 d.setdefault("foo") RuntimeError: key type not set: insert at least one item first
- Raises:
TypeError – if
type(key)does not match the type of the first key inserted.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = ("bar", "baz") d.setdefault(100)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[29], line 5 3 d = SortedDict() 4 d["foo"] = ("bar", "baz") ----> 5 d.setdefault(100) TypeError: got key 100 of type <class 'int'>, want key of type <class 'str'>
- Raises:
ValueError – if
keyis not comparable with instances of its type.
from pysorteddict import SortedDict d = SortedDict() d[1.1] = ("racecar",) d.setdefault(float("nan"))
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[30], line 5 3 d = SortedDict() 4 d[1.1] = ("racecar",) ----> 5 d.setdefault(float("nan")) ValueError: got bad key nan of type <class 'float'>
- values() SortedDictValues¶
Return a dynamic view on the values in the sorted dictionary.
from pysorteddict import SortedDict d = SortedDict() values = d.values() d["foo"] = () print(values) d["bar"] = [100] print(values) d["baz"] = 3.14 print(values)
SortedDictValues([()]) SortedDictValues([[100], ()]) SortedDictValues([[100], 3.14, ()])
Sorted Dictionary Views¶
Sorted dictionary views are dynamic views on a sorted dictionary: they are immutable and cannot be used to mutate the sorted dictionary, but always reflect its current state.
There are three view types.
- class pysorteddict.SortedDictItems¶
A view representing a sorted set of key-value pairs. Instances of this type are returned by
SortedDict.items(), but it is not user-importable.- __len__() int¶
Return the number of key-value pairs in the sorted dictionary view.
The behaviour is equivalent to that of
len(d)wheredis the underlying sorted dictionary.
- __contains__(ob: Any) bool¶
Return whether
obis present in the sorted dictionary view.If
obis not a two-elementtuple, returnFalse. Otherwise, the behaviour is equivalent to that ofob[0] in d and d[ob[0]] == ob[1]wheredis the underlying sorted dictionary.
- __getitem__(index_or_slice: int | slice) Any¶
Return the key-value pair at the given index or those in the given slice. The behaviour is equivalent to indexing or slicing a
listcontaining the key-value pairs.from pysorteddict import SortedDict d = SortedDict() items = d.items() d["foo"] = () d["bar"] = [100] d["baz"] = 3.14 d["spam"] = {} d["eggs"] = "" print(d) print(items[0], items[2], items[4]) print(items[:3]) print(items[1:]) print(items[-3:3]) print(items[-5:4:2]) print(items[::-1])
SortedDict({'bar': [100], 'baz': 3.14, 'eggs': '', 'foo': (), 'spam': {}}) ('bar', [100]) ('eggs', '') ('spam', {}) [('bar', [100]), ('baz', 3.14), ('eggs', '')] [('baz', 3.14), ('eggs', ''), ('foo', ()), ('spam', {})] [('eggs', '')] [('bar', [100]), ('eggs', '')] [('spam', {}), ('foo', ()), ('eggs', ''), ('baz', 3.14), ('bar', [100])]
- __iter__() SortedDictItemsFwdIter¶
Return a forward iterator over the key-value pairs in the sorted dictionary view.
Modifications made while iterating over the key-value pairs have well-defined behaviour.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = () d["bar"] = [100] d["baz"] = 3.14 for key, value in d.items(): d[key] = f"spam_{value}" d["a_" + key] = f"eggs_{value}" if "foo" in d: del d["foo"] for key, value in d.items(): print(key, "->", value)
a_bar -> eggs_[100] a_baz -> eggs_3.14 bar -> spam_[100] baz -> spam_3.14
See the exceptions raised by
SortedDict.__delitem__()andSortedDict.clear()for the restrictions that apply.
- __reversed__() SortedDictItemsRevIter¶
Return a reverse iterator over the key-value pairs in the sorted dictionary view.
Modifications made while iterating over the key-value pairs have well-defined behaviour.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = () d["bar"] = [100] d["baz"] = 3.14 for key, value in reversed(d.items()): d[key] = f"spam_{value}" d["z_" + key] = f"eggs_{value}" if "bar" in d: del d["bar"] for key, value in d.items(): print(key, "->", value)
baz -> spam_3.14 foo -> spam_() z_baz -> eggs_3.14 z_foo -> eggs_()
See the exceptions raised by
SortedDict.__delitem__()andSortedDict.clear()for the restrictions that apply.
- class pysorteddict.SortedDictKeys¶
A view representing a sorted set of keys. Instances of this type are returned by
SortedDict.keys(), but it is not user-importable.- __len__() int¶
Return the number of keys in the sorted dictionary view.
The behaviour is equivalent to that of
len(d)wheredis the underlying sorted dictionary.
- __contains__(ob: Any) bool¶
Return whether
obis present in the sorted dictionary view.The behaviour is equivalent to that of
ob in dwheredis the underlying sorted dictionary.
- __getitem__(index_or_slice: int | slice) Any¶
Return the key at the given index or those in the given slice. The behaviour is equivalent to indexing or slicing a
listcontaining the keys.from pysorteddict import SortedDict d = SortedDict() keys = d.keys() d["foo"] = () d["bar"] = [100] d["baz"] = 3.14 d["spam"] = {} d["eggs"] = "" print(d) print(keys[0], keys[2], keys[4]) print(keys[:3]) print(keys[1:]) print(keys[-3:3]) print(keys[-5:4:2]) print(keys[::-1])
SortedDict({'bar': [100], 'baz': 3.14, 'eggs': '', 'foo': (), 'spam': {}}) bar eggs spam ['bar', 'baz', 'eggs'] ['baz', 'eggs', 'foo', 'spam'] ['eggs'] ['bar', 'eggs'] ['spam', 'foo', 'eggs', 'baz', 'bar']
- __iter__() SortedDictKeysFwdIter¶
Return a forward iterator over the keys in the sorted dictionary view.
Modifications made while iterating over the keys have well-defined behaviour.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = () d["bar"] = [100] d["baz"] = 3.14 for key in d: d[key] = "spam" d["a_" + key] = "eggs" if "foo" in d: del d["foo"] for key, value in d.items(): print(key, "->", value)
a_bar -> eggs a_baz -> eggs bar -> spam baz -> spam
See the exceptions raised by
SortedDict.__delitem__()andSortedDict.clear()for the restrictions that apply.
- __reversed__() SortedDictKeysRevIter¶
Return a reverse iterator over the keys in the sorted dictionary view.
Modifications made while iterating over the keys have well-defined behaviour.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = () d["bar"] = [100] d["baz"] = 3.14 for key in reversed(d): d[key] = "spam" d["z_" + key] = "eggs" if "bar" in d: del d["bar"] for key, value in d.items(): print(key, "->", value)
baz -> spam foo -> spam z_baz -> eggs z_foo -> eggs
See the exceptions raised by
SortedDict.__delitem__()andSortedDict.clear()for the restrictions that apply.
- class pysorteddict.SortedDictValues¶
A view representing an array of values ordered by the keys they are mapped to. Instances of this type are returned by
SortedDict.values(), but it is not user-importable.- __len__() int¶
Return the number of values in the sorted dictionary view.
The behaviour is equivalent to that of
len(d)wheredis the underlying sorted dictionary.
- __contains__(ob: Any) bool¶
Return whether
obis present in the sorted dictionary view.The behaviour is equivalent to that of
ob in lwherelis alistof the elements in the view in the same order. In other words, making this call leads to an element-by-element comparison.
- __getitem__(index_or_slice: int | slice) Any¶
Return the value at the given index or those in the given slice. The behaviour is equivalent to indexing or slicing a
listcontaining the values.from pysorteddict import SortedDict d = SortedDict() values = d.values() d["foo"] = () d["bar"] = [100] d["baz"] = 3.14 d["spam"] = {} d["eggs"] = "" print(d) print(values[0], values[2], values[4]) print(values[:3]) print(values[1:]) print(values[-3:3]) print(values[-5:4:2]) print(values[::-1])
SortedDict({'bar': [100], 'baz': 3.14, 'eggs': '', 'foo': (), 'spam': {}}) [100] {} [[100], 3.14, ''] [3.14, '', (), {}] [''] [[100], ''] [{}, (), '', 3.14, [100]]
- __iter__() SortedDictValuesFwdIter¶
Return a forward iterator over the values in the sorted dictionary view.
Modifications made while iterating over the values have well-defined behaviour.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = () d["bar"] = [100] d["baz"] = 3.14 for value in d.values(): d[f"a_{value}"] = f"spam_{value}" d["eggs"] = value if "foo" in d: del d["foo"] for key, value in d.items(): print(key, "->", value)
a_3.14 -> spam_3.14 a_[100] -> spam_[100] bar -> [100] baz -> 3.14 eggs -> 3.14
See the exceptions raised by
SortedDict.__delitem__()andSortedDict.clear()for the restrictions that apply.
- __reversed__() SortedDictValuesRevIter¶
Return a reverse iterator over the values in the sorted dictionary view.
Modifications made while iterating over the values have well-defined behaviour.
from pysorteddict import SortedDict d = SortedDict() d["foo"] = () d["bar"] = [100] d["baz"] = 3.14 for value in reversed(d.values()): d[f"z_{value}"] = f"spam_{value}" d["eggs"] = value if "bar" in d: del d["bar"] for key, value in d.items(): print(key, "->", value)
baz -> 3.14 eggs -> 3.14 foo -> () z_() -> spam_() z_3.14 -> spam_3.14
See the exceptions raised by
SortedDict.__delitem__()andSortedDict.clear()for the restrictions that apply.