Creating and manipulating dictionaries in Python 3

Stores information using a key and a value. Consider the following:

Key     | Value

Chicken | A flightless bird

House   | A structure to live in

Tree    | A thing with leaves

Creating a dictionary

Creating using curly brackets, the key and value are separated via a colon, and each key-value pairis separated with a comma:

newDict = {'Chicken ':'A flightless bird',

           'House   ':'A structure to live in', 

           'Tree    ':'A thing with leaves'}

Looking up a key value

Given the example above, if we wanted to look up the value for the key ‘Chicken’, we would write:

print(newDict['Chicken'])

This would return:

'A flightless bird'

Types

Dictionaries can store any mixture of types:

Strings to Strings

newDict = { 'Chicken' : 'A flightless bird' ,

            'House' : 'A structure to live in' }

Strings to Numbers

newDict = { 'Chips' : 3 ,

            'Burger' : 7 }

Mixture of types

newDict = { 50.43 : 'A flightless bird' ,

            5 : 65 }

Adding entries to a dictionary

We’ll start with an empty dictionary:

newDict = {}

Then we can add key-value pairs using the below syntax:

newDict['key'] = 'value'

This also works for updating the value for a key that already exists.

Removing dictionary items

To remove the ‘Chicken’ key-value pair from the below dictionary:

newDict = {'Chicken ':'A flightless bird',

           'House   ':'A structure to live in', 

           'Tree    ':'A thing with leaves'}

We can use the 'del' command:

del newDict['Chicken']

The updated dictionary will be:

newDict = {'House   ':'A structure to live in', 

           'Tree    ':'A thing with leaves'}

Avoiding a ‘KeyError’

If you try to access a value that does not exist in the list, the program will crash and return a keyError. To avoid this we use the ‘.get’ method:

result = newDict.get('mouse')

print(result)

  • None

If the above word is not in the dictionary, 'None' will be returned, and the program will continue to run.

In Python, ‘None’ is a unique value that signifies the absence of a value.  It evaluates to Falsein a conditional statement and the presence of a value evaluates to True:

newDict = {'Chicken ':'A flightless bird',

           'House   ':'A structure to live in', 

           'Tree    ':'A thing with leaves'}

result = newDict.get('mouse')

if result:

  print(result)

else:

  print('Key does not exist')

In the above example, we are looking for a key ‘mouse’, however, because we use the ‘.get’ function and the key do not exist in the list, the ‘None’ value is returned. Moving on to the conditional statement, we are checking if the result is true (if result:) then print the result, however, in this case, the result is false so we print the warning ‘Key does not exist’.