Reputation: 355
Basically, I wonder what happens or might happen under the hood when I run something like this:
for key in some_hash_map.keys():
print(key)
Is it just about using a reversed hash function?
Upvotes: 1
Views: 608
Reputation: 46408
A typical hash table can be implemented as an array of buckets, each of which has a linked list of entries.
A hash lookup goes by running the hash function to find the right bucket, then searching the bucket.
Iterating over the keys is implemented by iterating over the buckets, searching each list in turn.
If there are too many buckets, you waste memory and iteration is slow. Too few, and the linked lists get slow. But we can dynamically resize the number of buckets for fixed per key overhead.
If the hash function fails to work well, then a hash will perform terribly.
Upvotes: 3