I would like to use a type that behaves like a simple list of pairs [(a,b)]
that serves as a dictionary, mapping keys of type a
to values of type b
, while maintaining a "user-specified", defined order of keys. (i.e. just as with ordinary lists - I would like to be able to "append" an item which is then recognized as the "last element".) However I would like random access lookup on keys with better than linear performance, i.e. what Data.Map
provides. One option would be to just maintain an ordinary map in addition to a list of keys that defines their order:
data OrderedDict a b = OrderedDict (Map a b) [a]
and then define append
operations, etc. that keep the two key collections in sync. It seems ugly though to maintain two separate collections of the same keys. Is there a ready-made data type that already combines ordered keys with efficient random-access lookup by key?
As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default. This is considered an implementation detail though; you should still use collections. OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python.
Dictionary keys must be of an immutable type. Strings and numbers are the two most commonly used data types as dictionary keys. We can also use tuples as keys but they must contain only strings, integers, or other tuples.
It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not.
How to Define a Dictionary: Dictionaries are generally defined in Python by a list of comma-separated key-value pairs wrapped around curly braces ({}). Each key is separated from its associated value by a colon (:). You can also define a dictionary by using its constructor, dict() .
Take a look at ixset
library - it allows you to maintain sets indexed by multiple columns (by a
and by Int
in your case). This is much more maintainable than keeping maps consistent by hand
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With