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:

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

The same can be created using the dict keyword:

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

A third way to create and populate this:

1
2
3
4
ages = {}
ages["Bob"] = 25
ages["James"] = 54
ages["Darren"] = 44

Accessing values

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# 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.

1
del ages["James"]

This will result in the following output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# 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}