The Python dictionary: Python’s native hash table

When it comes to using data structures in your coding and development career, whether that be recreational or professional, a hash table is the most efficient way to be able to store and retrieve specific data. This is done by creating an array larger then the amount of data you plan on storing in it, creating a unique integer array representation of the key that fits within the bounds of the array through a hashing algorithm and taking a modulus (remainder in basic division) of that integer with our array length, and storing our key, value pair within that index of the array.

Imagine you are running an online social network with 1,000,000 customers and you want to figure out the email address of one specific user. Rather then looking through all your users, one at a time, until you find the row that matches the user screen name you are looking and getting that email; you can use a hash table which uses the username as the key and the email address as it’s value. Now you simply need to do user[username] to get a person’s email in o(1) constant time.

You can also have the value of your hash table be an object to return email address, physical address, gender, date of birth, etc.. and be able to create a whole page about that user. This is the basis behind database indexes and querying your users table to create a web page about that user.

Using the python dictionary

Python’s official reference

# Dictionary declarations
bracket_notation_dict = {}
object_notation_dict = dict()

# Creating dictionaries with existing data
initialized_dict_1 = {1 : "a", 2: "b"}
initialized_dict_2 = dict(one="a", two="b")

# Adding values to our dictionary
initialized_dict1[3] = "c"

# Deleting values from our dictionary
del initialized_dict1[3] 

# Reassigning values
initialized_dict_1[2] = "bee"

# Get a list of the keys
>> [1,2]

# Get a list of the values
>> ["a", "bee"]

# loop through our dictionary by key, value pairs
for key, value in initizlied_dict_1.items():
  print(key + " " + value)

>> 1 a
   2 bee  

Mapping between values

A common use case for python dictionaries that I run into in my professional development is the need to map between one string to another. This is generally to be able to find data from a user code name and then query data based on an internal id. Below is an example of doing this.

# Some toy imports to demonstrate a real world script
from team_notifications import send_alert
from metric_db_conn import database

# It's much easier to remember the code names then the ids
# internally
code_name_map = {
  "sparrow" : "a1b1c1",
  "robin" : "d2e2f2"

# Query data based on user input for device name
device_input_valid = False

while not device_input_valid:
  device = input("Enter device to check heat metric for")
  if device not in code_name_map:
    print("Device name not valid")
    continue # Let user enter name again
    device_input_valid = True # Break the input loop

hard_to_read_id = code_name_map[device]

# Imagine this returns a list of dictionaries with different
# metric data about our sparrow product
metrics = database.query_metrics(id=hard_to_read_id)

for metric in metrics:
  if metric["heat_in_celcius"] > 100:
    send_alert("%s is boiling" + device)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s