Using Dictionary Datatypes In Python

in STEMGeeks2 years ago

Welcome back to a new article in our series on getting started coding with Python. In our last article we covered one of the more advanced datatypes we can use in Python and this week we are going to move a little further with advanced datatypes by introducing Dictionaries.

Like we said Dictionaries are an advanced datatype we can use in Python and is used to store values as key: value pairs. Data within a Python Dictionary is ordered, changeable, but does not allow duplicates.

MAKE NOTE: Python versions prior to 3.7, Dictionaries were not ordered. This means you would not be able to use Dictionaries with an index number to present a value.

Working With Dictionaries

As we have been doing a good job of working through examples in the interactive shell, once again open up your shell and we will work through some examples and how we can incorporate Dictionaries into your Python code.

To create a Dictionary in Python, we use curly brackets{} and then list our keys and values. For example, below we have create a Dictionary name employee_one and then listed out three key value pairs in between the curly brackets. Make sure that each key value pair you have is separated by a comma(,) except for the last value as we have below:

>>> employee_one = {
... "Name": "Vince Sesto",
... "StaffNumber": 123,
... "Department": "Software Engineering"
... }
>>> type(employee_one)
<class 'dict'>

As you can see we have used different data types within our values in the Dictionary, as there is no restriction on the data types you can use. In the example above, we have used an integer for the value of StaffNumber, and strings for all of the other values. A colon(:) separates the key from the associated value.

>>> print(employee_one)
{'Name': 'Vince Sesto', 'StaffNumber': 123, 'Department': 'Software Engineering'}

If you need to refer to items in the Dictionary and present their values, this can be achieved by using the key name. In the example below, we have used "Name" in square brackets to present the value associated with the key:

>>> employee_one["Name"]
'Vince Sesto'

Duplicate values will be overwritten in your Dictionary, with the last value presented being the value that will be kept. You can print the length of a Dictionary using the len() function:

>>> len(employee_one)

We can add or change values in our Dictionary at any time by referring to the key name, or even adding a new key. In the example below, we have been able to change the Department name of the employee_one dictionary, and also added in the Title for the Dictionary:

>>> employee_one["Department"] = "Development"
>>> employee_one["Title"] = "Software Engineer"
>>> employee_one
{'Name': 'Vince Sesto', 'StaffNumber': 123, 'Department': 'Development', 'Title': 'Software Engineer'}

We can also delete items in our Dictionary by using the del function. In the example below, we have been able to delete the StaffNumber key value pair. Make note that the del function does not use brackets and is simply followed by the key you want to remove:

>>> del employee_one["StaffNumber"]
>>> employee_one
{'Name': 'Vince Sesto', 'Department': 'Development', 'Title': 'Software Engineer'}

Multiple Levels of Dictionaries

As we mentioned earlier, we can add any data type into our Dictionary. This means we can also have Lists and Dictionaries as values. We can explain this best with another example as we have below. We can see we have added a new key to our employee_one Dictionary of "Appearance" and added a Dictionary as the value with all the relevant key value pairs, including eye colour, hair colour and if the employee wears glasses.

>>> employee_one["Appearance"] = { "eye colour": "brown", "hair colour": "brown", "glasses": True}
>>> employee_one
{'Name': 'Vince Sesto', 'Department': 'Development', 'Title': 'Software Engineer', 'Appearance': {'eye colour': 'brown', 'hair colour': 'brown', 'glasses': True}}

As you can see the value for glasses is being represented as a True|False Boolean value. We can then reference values from this second Dictionary by adding a second set of square brackets and requesting the value from the specific key as we have below:

>>> employee_one["Appearance"]["glasses"]

Testing The Dictionary Values

We are just going to finish off this article with some built in functions available when using Dictionaries. You may want to test your Dictionary to verify it has a specific key available in it. As you can see below, we can use "in" or "not in" if we wanted to test our Dictionary and provide a True or False result. We have used the shell to test but this would easily be able to be used in an if statement too:

>>> "StaffNumber" in employee_one
>>> "Name" in employee_one

The items() function provides all the key values stored in the Dictionary and places them in separate Tuples:

items() returns a list of tuples containing the key-value pairs of the Dictionary
>>> employee_one.items()
dict_items([('Name', 'Vince Sesto'), ('Department', 'Development'), ('Title', 'Software Engineer'), ('Appearance', {'eye colour': 'brown', 'hair colour': 'brown', 'glasses': True})])

The keys() function provides a list of all the keys in the Dictionary:

keys() returns a list of all keys in the dictionary
>>> employee_one.keys()
dict_keys(['Name', 'Department', 'Title', 'Appearance'])

The values() function does a similar job but outputs all of the values. In our example below, we have used a Loop to print them out separately if needed.

>>> for i in employee_one.values():
...   print(i)
Vince Sesto
Software Engineer
{'eye colour': 'brown', 'hair colour': 'brown', 'glasses': True}

As you can see, if we simply use the values() function on its own, we something similar to the output below:

>>> employee_one.values()
dict_values(['Vince Sesto', 'Development', 'Software Engineer', {'eye colour': 'brown', 'hair colour': 'brown', 'glasses': True}])

Finally the clear() function will clear all the values out of the Dictionary, still leaving the Dictionary available to be used and added to, but all the previous values will be removed:

>>> employee_one.clear()
>>> employee_one

We made some good progress here. We covered off Dictionaries and how we can start using them as part of our Python code. You might not want to use them as yet, but it is good to get used to them as they offer a lot of flexibility when wanting to hold a variety of different data in one container.

Posted with STEMGeeks


Dictionaries can be really powerful. I used some in my Brit list script as I can generate charts with them. The keys get used to label values. Do have to be sure to spell the keys right when you reference them though.


Thanks @steevc I almost was a little worried about using them originally. I think I was just a little unclear on how useful they were.

Hi, you were just shared some LUV thanks to @steevc. Holding 10 LUV in your wallet enables you to give up to 3 LUV per day, for free. See the LUV in your wallet at or learn about LUV at