A dictionary is a collection of values that are stored in key : value format. Where a key is associated with a value, or a list of values. By default, the values within a dictionary are not stored in order.

To create an empty dictionary you use the curly brackets “{}”.

dct = {}

 

Let’s create a dictionary with values for our examples.

dct = {"Cats" : ['Rajah', 'Kiara', 'Simba'], "Dogs" : ['Goose', 'Bear', 'Chewy', 'Diva'], "Humans" : "Mum"}

 

Dictionary Methods

Dictionaries have built in methods that are useful. Here are a few of them:

Method Description
dictionary_name.keys() Returns the keys in a list
dictionary_name.values() Returns the values in a list
dictionary_name.items() Returns the key, value pairs (as tuples) in a list
dictionary_name.get(key, default_value) Searches a dictionary for a key and returns
an assigned default value if key is not found
dictionary_name.update(dct2) Adds dct2’s key-value pairs to existing dictionary
dictionary_name.pop() Removes a key and it’s values from a dictionary.
Also, returns the values removed.
dictionary_name.clear() Removes all keys and values

Indexing

Dictionaries are indexed with a key instead of with a number (like lists or strings). When you want a value from the dictionary, you retrieve the value by using the key. If there are multiple values associated with a single key, the output will be all the values that are associated with the key in a list. The list can be indexed or sliced itself – remember Python starts the index at 0.

dct['Cats']
[‘Rajah’, ‘Kiara’, ‘Simba’]

 

dct['Cats'][2]
‘Simba’

 

Remember that when you are slicing with Python, you get 1 minus the number you entered.

dct['Cats'][:2]
[‘Rajah’, ‘Kiara’]

 

Counting with Dictionaries

A common use with dictionaries is to count items. If you are unfamiliar with for loops and iterations, take a look at our page.

This is made easy with the .get() method. Let’s dive in.

counts = dict()
names = ['Olivia', 'Josh', 'Michael', 'Olivia', 'Jordan', 'Josh', 'Mike', 'Olivia']

for name in names :
    counts[name] = counts.get(name, 0) + 1

 

Let’s break down the example:

1) First we created an empty dictionary to hold our future counts.
2) Next we see the list of names we will be working with.
3) Then comes the for loop which contains the .get() method.

The for loop is iterating through the list. For every iterated value (we called it “name”), it creates an entry in our dictionary (counts) with the “name” value. This new entry is now our key in the dictionary. The .get() method is assigning a default value of 0 with they key if it does not already exist. If it exists, 1 is being added to the current count for that key.

print(counts)
{‘Josh’: 2, ‘Jordan’: 1, ‘Olivia’: 3, ‘Mike’: 1, ‘Michael’: 1}

 

Sorting Dictionaries by Keys

Notice how the results were not in any type of sorted order. If we want to sort the values we need to use the sorted() function in combination with the .items() method. This will sort the values based on alphabetical order and output both the key and value in a pair called a tuple in a list.

print(sorted(counts.items()))
[(‘Jordan’, 1), (‘Josh’, 2), (‘Michael’, 1), (‘Mike’, 1), (‘Olivia’, 3)]

 

Sorting Dictionaries by Values

In order to sort a dictionary by values we need to use a lambda.

print(sorted(counts.items(), key=lambda x: x[1])
[(‘Jordan’, 1), (‘Mike’, 1), (‘Michael’, 1), (‘Josh’, 2), (‘Olivia’, 3)]

 

We can also sort it in descending order by using the reverse parameter.

print(sorted(counts.items(), key=lambda x: x[1], reverse=True))
[(‘Olivia’, 3), (‘Josh’, 2), (‘Jordan’, 1), (‘Mike’, 1), (‘Michael’, 1)]