Introduction to Dictionaries

Updated on 28 Dec 2022

A Dictionary are synomonous with arrays in other languages. They have a key and value, and of course the key must be unique. list uses the [] square brackets, and dict uses the {} curly brackets for the definition (then normal square brackets later during access).

#list
student_list = ['brent', 'paul', 'andrea']

#set
student_set = {'brent', 'paul', 'andrea'}

Typical example

The example above is not the way you’d use a dictionary because we haven’t specified a key. (If you’re not using a key, then just use a list). The key is used to describe the data. I.e.

myData = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

print(myData['Name'])
print(myData['Age'])

You can even format your dictionary to make it more readable.

myData = {
    'Name': 'Zara', 
    'Age': 7, 
    'Class': 'First'
    }

print(myData['Name'])
print(myData['Age'])

Update or add Elements

Of course you can update the elements after they’ve been defined.

myData = {
    'Name': 'Zara', 
    'Age': 7, 
    'Class': 'First'
    }

myData['Age'] = 70

print(myData['Age'])

We can add new elements to an existing dictionary in a similar way to updating an existing element.

myData = {
    'Name': 'Zara', 
    'Age': 7, 
    'Class': 'First'
    }

myData['Rating'] = 10

print(myData)

Delete elements

If for any reason you need to remove an element, you can do that too.

myData = {
    'Name': 'Zara', 
    'Age': 7, 
    'Class': 'First'
    }

del myData['Age']

print(myData)

An alternative means of deleting an element is with the pop method.

myData.pop('Age')

Looping 1

Similar to what we’ve seen with the list, we can loop thru a dictionary. This is particular useful if we need to operate on each element or we are unsure of the key values.

myData = {
    'Name': 'Zara', 
    'Age': 7, 
    'Class': 'First'
    }

for key in myData:
    print(key, ':', myData[key])

Looping 2

An alternative method is using the items() method which will return the key and value.

myData = {
    'Name': 'Zara', 
    'Age': 7, 
    'Class': 'First'
    }

for key, value in myData.items():
    print(key, ':', value)