BenMorganIO BenMorganIO - 1 year ago 78
Python Question

What is the difference between a Ruby Hash and a Python dictionary?

In Python, there are dictionaries:

residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}

In Ruby, there are Hashes:

residents = {'Puffin' => 104, 'Sloth' => 105, 'Burmese Python' => 106}

The only difference is the
syntax. (Note that if the example were using variables instead of strings, then there would be no syntax difference.)

In Python, you call a dictionary's value via a key:

# => 104

In Ruby, you grab a Hash's value via a key as well:

# => 104

They appear to be the same.

What is the difference between a Hash in Ruby and a dictionary in Python?

Answer Source

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.

Of course there are lots of detail differences between the two..

  • Default behavior on missing key look-up: nil in Ruby, exception in Python
  • Insertion-ordering guarantees: guaranteed in Ruby 2, no guarantee in dict
  • Being able to specify a default value generator: Ruby only
  • Ability to use core mutable types (e.g. lists) as keys: Ruby only
  • (And I'm sure there are more.)

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.