Both Ruby's Hash and Python's dictionary represent a Map Abstract Data Type (ADT)
.. an associative array, map, symbol table, or dictionary is an abstract data type composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection.
Furthermore, both Hash and dictionary are implemented as Hash Tables which require that keys are hashable and equatable. Generally speaking, insert and delete and fetch operations on a hash table are O(1) amortized or "fast, independent of hash/dict size".
[A hash table] is a data structure used to implement an associative array, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found.
(Map implementations that use Trees, as opposed to Hash Tables, are found in persisted and functional programming contexts.)
Of course, there are also differences between Ruby and Python design choices and the specific/default Map implementations provided:
- Default behavior on missing key lookup:
nil
inHash
, exception indict
1 - Insertion-ordering guarantees: guaranteed in
Hash
(since Ruby 2.0), no guarantee indict
(until Python 3.6)1 - Being able to specify a default value generator:
Hash
only1 - Ability to use core mutable types (eg. lists) as keys:
Hash
only2 - Syntax used for Hash/dict Literals, etc..
The []
syntax support is common insofar as both languages provide syntactic sugar for an overloaded index operator, but is implemented differently underneath and has different semantics in the case of missing keys.
1 Python offers defaultdict
and OrderedDict
implementations as well which have different behavior/functionality from the standard dict
. These implementation allow default value generators, missing-key handling, and additional ordering guarantees that are not found in the standard dict
type.
2 Certain core types in Python (eg. list
and dict
) explicitly reject being hashable and thus they cannot be used as keys in a dictionary that is based on hashing. This is not strictly a difference of dict
itself and one can still use mutable custom types as keys, although such is discouraged in most cases.