HashMaps (Aka: Dictionaries) in Python


Introduction

Java has a built-in called HashMap. It allows you to store and very quickly retrieve key value pairs.

In Python, this is called a dictionary and appears very similar to a JSON Object for those familiar with Javascript and similar languages.

Dictionaries as HashMaps

An example of a dictionary in Python is as follows:

ages = {"Bob":25, "James":54, "Darren":44}

The same can be created using the dict keyword:

ages = dict({"Bob":25, "James":54, "Darren":44})

A third way to create and populate this:

ages = {}
ages["Bob"] = 25
ages["James"] = 54
ages["Darren"] = 44

Accessing values

As per our last creation option, accessing is much the same.

# get james' age
james = ages["James"]

# it is safer to do it this way
james = 0
if "James" in ages:
  james = ages["James"]

# or simply
james = 0 if "James" not in ages else ages["James"]

Deleting a value

Deleting a value is as simple as calling the key with the del keword.

del ages["James"]

This will result in the following output:

# create our dictionary/hashmap
ages = {"Bob":25, "James":54, "Darren":44}

# delete James' entry
del ages["James"]

# let's see what the dictionary contains now
print(ages)

# {'Bob': 25, 'Darren': 44}