HashMaps (aka: Dictionaries) in Python


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}
Code language: Python (python)

The same can be created using the dict keyword:

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

A third way to create and populate this:

ages = {} ages["Bob"] = 25 ages["James"] = 54 ages["Darren"] = 44
Code language: Python (python)

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"]
Code language: Python (python)

Deleting a value

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

del ages["James"]
Code language: Python (python)

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}
Code language: Python (python)
Notify of
Inline Feedbacks
View all comments