Categories
Python

Python Dictionary: A Data Collection Type (Part 3 of 3)

Image for post
Photo by Pisit Heng on Unsplash

If you are to remember one thing from this article, it is to remember that a python dictionary stores data in “key to value” pairs. This means that for every key in the dictionary there is a corresponding value. This value can be any type of data object (another dictionary, list, tuple, integer, string, boolean, etc.); however, the keys must be unique and an immutable type (string, number, or tuple with immutable elements).

I like to think of dictionaries as a key and lock system. You have the one key that can unfasten the lock which can hold any number of things, but that key is very specific. This is the simplest analogy for me since you already are using the word “key” in the python definition.

Image for post
Photo by Jaye Haych on Unsplash

The Python dictionary is unordered, meaning that you cannot access values through the index (as you might with a list or tuple), but you must access them through the key.

In this Article:

  1. Accessing Elements
  2. Adding/Deleting Elements

Creation Time!!

The python dictionary likes to be fancy. It has special keys that need to be called to return items, so it needs a fancy way to enclose the items inside it. It uses the curly brackets {}. You can almost see the progression here from the most basic to the most complex data type. The tuple is immutable collection of data and uses the most basic symbol the parentheses (). The list is a step up since it is mutable and can be changed and thus uses the brackets []. The last step for the most complex of the data types is the dictionary and uses the fanciest symbol the curly brackets {}.

The reason I bring this up is that that is how you can make a blank python dictionary, by using {}.

blank_dict = {}

OUTPUT:

example creation of python dictionary

A blank dictionary is useful if you want to use a function or for loop to fill the dictionary with data later on.

Next, the dictionary can be created using the data listed in key: value pairs. Like mentioned before, the keys must be of immutable types such as a string, integer or tuple, but the values can be of any type. In our first example, imagine Eleanor is studying different anatomical aspects of Eastern Bluebirds (a threatened species). She measures body length, wingspan, and weight. The first bird measures 16 cm, 25cm, 27g, respectively. Eleanor then places this information into her python dictionary.

Image for post
Image by Naturelady from Pixabay
bb_measurements = {‘length’: 16, ‘wingspan’: 25, ‘weight’: 27}

OUTPUT:

example of the creation of a python dictionary

In this initial example, we are using strings as the immutable object for the dictionary keys; however, they could also be numbers or a tuple. I will show them below; however, they don’t make sense in terms of the current example, but I will still show the possibility here.

bb_measurements = {1: 16, 2: 25, 3: 27}

OUTPUT:

example of the creation of a python dictionary wit numeric keys

This is also a point where it can get a little confusing. Since you are able to use numbers as the keys in a dictionary, it can appear like you are using the index to reference the keys in the dictionary. However, this is not the case. If you really want the keys to be referenced by a number you have to input the keys as you do above. You cannot automatically refer to them as this like you would be able to with an index in a list.

bb_measurements = {(‘length’,’cm’): 16, (‘wingspan’, ‘cm’): 25, (‘weight’, ‘g’): 27}

OUTPUT:

shows the example of the creation of a python dictionary with tuples as keys

Using a tuple as a key may be useful if you need to denote multiple parts to a key if you might then be putting the dictionary into a multi-indexed dataframe; however, the idiosyncrasies of this are beyond the scope of this article.

You can also create a dictionary with any type as the value, it doesn’t have to be restricted to numbers, but can be strings, boolean, lists, additional dictionaries, etc. Similar to lists, they do not have to all be the same either, thus you can have a value with a list, the next value as an integer, and the next as another dictionary. Making dictionaries extremely versatile.

Accessing Python Dictionary Elements

bb_measurements[‘weight’]

OUTPUT:

example of using the key in a python dictionary

Alternatively, she could also use the .get() method:

bb_measurements.get(‘weight’)

OUTPUT:

example of using the .get() method in a python dictionary

Either method works great. The only difference is that if you try to call a key that is not in the dictionary, you will receive a ValueError with the brackets, while you will receive “None” from the .get() method.

bb_measurements[‘hi’]bb_measurements.get(‘hi’)

OUTPUT:

shows how there is an error in a python dictionary

The difference between the two results might be useful to you depending on what return you are looking for when you are using the dictionary in a function.

Adding Python Dictionary Elements

bb_measurements['tarsus'] = 6.3

OUTPUT:

adding in an element in a python dictionary

If Eleanor realizes after looking back at her notes that the bluebird actually was 16.1 cm long not just 16, she can update the value in the dictionary by using the same process and the 16 will be replaced with a 16.1.

bb_measurements['length'] = 16.1

OUTPUT:

shows how to replacing one of the elements in a python dictionary

Deleting Python Dictionary Elements

  1. del
  2. .pop()
  3. .popitem()

If she wants to clear the whole dictionary and start over, she can use the .clear() method.

Eleanor can use the “del” keyword to remove a single item or delete the entire dictionary.

del bb_measurements['tarsus']

OUTPUT:

shows the use of delete in a python dictionary

.pop() method will remove the item from the dictionary and return the value.

bb_measurements.pop('tarsus')

OUTPUT:

details what pop does in a python dictionary

popitem() method will remove the item that was last added to the dictionary and return the key and value as a tuple.

bb_measurements.popitem()

OUTPUT:

details what popitem does in a python dictionary

Now Eleanor has her dictionary for her Eastern Bluebird all in order, my hope is that you do as well.

Image for post
Image by Naturelady from Pixabay
Still confused? Contact me to schedule a consultation to get control of your data.

Check out Part 1 of the Series on Lists here.

Check out Part 2 of the Series on Tuples here.

This article was originally posted on Medium.

2 replies on “Python Dictionary: A Data Collection Type (Part 3 of 3)”

Comments are closed.