Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A dictionary type with a defined order of keys

Tags:

haskell

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?

like image 810
gcbenison Avatar asked Jun 08 '12 01:06

gcbenison


People also ask

What is the order of keys in Python dictionary?

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.

What data type is a dictionary key?

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.

Is dictionary in sorted order?

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 do you define a key dictionary?

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() .


1 Answers

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

like image 188
nponeccop Avatar answered Sep 25 '22 23:09

nponeccop