import collections


def group_by_hash(values, hash_fn=hash, store_index=False):
  """Groups values by their hash value.

  Args:
    values: An iterable of any objects.
    hash_fn: A function that is called to compute the hash of values.
    store_index: Whether to store the index of values or values in the returned
      dict.

  Returns:
    A `collections.OrderedDict` mapping hashes to values with that hash if
    `store_index=False`, or value indices otherwise. The length of the map
    corresponds to the number of unique hashes.
  """
  groups = collections.OrderedDict()
  for idx, value in enumerate(values):
    to_store = idx if store_index else value
    groups.setdefault(hash_fn(value), []).append(to_store)
  return groups