Dictionaries

Like a list, a dictionary is a data structure which can be used to collect multiple values. While the indices of lists consist of numbers which are assigned automatically, the indices of dictionaries can be of any value type, and programmers also need to define these indices themselves.

A dictionary can be created using the dict() function. This function results in an empty dictionary. Elements can be added to the dictionary by using the bracket operator containing the index. Importantly, each of these indices must be unique. The value associated with this index needs to be given after the assignment operator.

In [ ]:
data = dict()

data['firstName'] = 'William'
data['lastName'] = 'Shakespeare'
data['yearOfBirth'] = 1564

print( data['firstName'] + ' ' + data['lastName'] )
## This prints 'William Shakespeare'

As can be seen in the code above, the individual values in dictionaries can be accessed by using their indices. When you mention an index that does not actually exist, however, the code produces an error. It is evidently impossible to make use of an index which does not exist. To avoid such error messages, you can make use of the get() method. This method requires two values. Firstly, you need to mention the index of the element that you want to retrieve. Secondly, you have to provide a default value which should be returned when the index that was supplied does not exist.

In [ ]:
print( data.get( 'yearOfBirth' , 'NULL' ) )
# prints 'NULL' is the variable data['yearOfBirth'] has not been set yet.

print( data.get( 'numberOfChildren' , 0 ) )
# prints 0 is the variable data['numberOfChildren'] has not been set yet.

Dictionaries can also be populated upon their creation using a syntax that makes use of curly brackets. Within this brackets, you need to list all the needed key and value pairs. The keys and the values need to be separated by a colon. All individual items in the dictionary (i.e. the full key and value pairs) need to separated by a comma. The example below offers an example.

In [ ]:
capitals = { 
    'France':'Paris', 
    'Spain':'Madrid',
    'The Netherlands' : 'Amsterdam' , 
    'Belgium':'Brussel' , 
    'Italy':'Rome',
    'Germany':'Berlin',
    'Denmark':'Copenhagen'
} 

As is the case for lists, you can iterate all the elements in a dictionary via the ‘for’ keyword.

In [ ]:
for c in capitals:
    print( 'The capital of {} is {}.'.format( c , capitals[c] ) )

Sorting a dictionary

By default, all the items in this dictionary are shown in the order in which they were added to the dictionary.

When you have created a dictionary named 'capitals', using the code above, it can be sorted by index using the in-built sorted() function. Strings are sorted alphabetically and integers and floats are sorted numerically.

In [ ]:
for c in sorted(capitals):
    print( 'The capital of {} is {}.'.format( c , capitals[c] ) )

Note that the code above sorts the dictionary by index. In this example, the sorting opertaion is based on the names of the countries. Sorting by value is slightly more complicated. Python does not contain an in-built function for sorting dictionaries by value, unfortunately. One solution is to create a new function which does offer this functionality. The cell below provides the code that can be used for this purpose.

The code as it is given in the 'sortedByValue()' function sorts the keys in an ascending order. To work with a descending order, you can use the output of the sortedByValue() function in the in-build reversed() function, as shown below. The first iteration produces a list which starts with Amsterdam, and which ends in Rome. The second iteration shows the same list, but in the inverse order.

In [ ]:
def sortedByValue( dict ):      
    return sorted( dict , key=lambda x: dict[x]) 
    

for country in sortedByValue(capitals):
    print( capitals[country])

print('\n\n')
    
for country in reversed(sortedByValue(capitals)):
    print( capitals[country] )