Dictionaries in Python

Thomas
3 min readDec 27, 2020

To continue on from learning about lists we’ll now extend to another data type. Dictionaries.

There are several commonalities here. Dictionaries are mutable and can be moulded in many ways. They can also be ‘nested’ meaning that a dictionary can contain another dictionary.

When we extract specific items from a list we use indexes.

With dictionaries we access ‘keys’.

Dictionaries contain a ‘key’ and a ‘value’ (forming a pair).

A shown below, dictionaries are written with curly braces, a colon seperating the key/value and a comma seperating each pair.

Dictionary = {

'Uno': 1, 'Uno' = KEY | 1 = VALUE
'Dos': 2,
'Tres': 3,

}

Similar to a list, we can print the entire dictionary:

print(Dictionary)--------------------------------------------------------------------{'Uno': 1, 'Dos': 2, 'Tres': 3}

As mentioned, to access a value we will use the relevant key.

print(Dictionary['Uno'])--------------------------------------------------------------------1

To add the number four, it’s pretty simple. We just assign it to the dictionary object.

Dictionary['Cuatro'] = 4
print(Dictionary)
--------------------------------------------------------------------{'Uno': 1, 'Dos': 2, 'Tres': 3, 'Cuatro': 4}

Say we changed our mind and didn’t actually want the 4. Use ‘del’ (specifying the key again) to delete it.

del Dictionary['Cuatro']
print(Dictionary)
--------------------------------------------------------------------{'Uno': 1, 'Dos': 2, 'Tres': 3}

Similar to an empty list, you can formulate the dictionary as you go. There may be circumstances when you will need to continually add data to it. Begin with an empty dictionary {}.

D = {}

D['Sport'] = 'Rugby'
D['Team'] = 'New Zealand'
D['Nick-Name'] = 'All Blacks'
D['Example Players'] = ['Aaron Smith', 'Rieko Iaone']

In the ‘Example Players’ we have 2 names for the ‘value’. Here we DO use an index to access a specific name as shown below:

print(D['Example Players'][0])--------------------------------------------------------------------Aaron Smith

The example below introduces a parameter (Geography) that includes:

(1) Different data types (boolean and integer)

(2) Multiple items (S.Hemisphere and Population)

D['Geography'] = {'S.Hemisphere': True, 'Population': 4800000}

We’ll access the population value like this (quite intuitive):

print(D['Geography']['Population'])--------------------------------------------------------------------4800000

and….

print(D['Geography']['S.Hemisphere'])--------------------------------------------------------------------True

We said dictionaries are dynamic and useful. Boolean, string and integers can be used. But we can take this one step further and include objects. Python is an object orientated language so this will likely be a useful tool when using dictionaries.

Fruit = 'Banana'

D = {Fruit: 'Yellow'}
print(D)
--------------------------------------------------------------------{'Banana': 'Yellow'}

In the example below, we’ve given our lucky player a straight in poker using objects as ‘keys’.

Heart = '♡'
Diamond = '♢'
Club = '♧'
Spades = '♤'

Cards = {}

Cards[2] = Heart
Cards[3] = Diamond
Cards[4] = Club
Cards[5] = Spades
Cards[6] = Heart

print(Cards)
--------------------------------------------------------------------{2: '♡', 3: '♢', 4: '♧', 5: '♤', 6: '♡'}

Remember here — The numbers 2–6 are NOT indexes despite appearing so at first glance. They are actually designated ‘keys’. The keys correspond to a numbered playing card. If you caught this, well done!

We can return booleans on specific statements as well (using the keys).

print(7 in Cards)
print('Ace' not in Cards)
--------------------------------------------------------------------False
True

Dictionary Tailored Methods

Similar to lists, python contains specific methods that can be used to manipulate a dictionary. Some are identical to those of list methods and many are intuitive.

GET

‘Get’ extracts a value from a given key. If it doesn’t exist, an error doesn’t actually get thrown. The argument required in the parentheses is the key.

D = {'Uno': 1, 'Dos': 2, 'Tres': 3}

print(D.get('Dos'))
--------------------------------------------------------------------2

ITEMS

Items will return tuples of the key/value pair. No arguments are inserted into the parantheses.

print(D.items())--------------------------------------------------------------------dict_items([('Uno', 1), ('Dos', 2), ('Tres', 3)])

Easily access a specific pair by converting this into a list and then utilising the index feature.

print(list(D.items())[0])--------------------------------------------------------------------('Uno', 1)                                  #RETURNS A TUPLE

KEYS

Specify the key (an easy one).

print(D.keys())
print(list(D.keys())[-1])
--------------------------------------------------------------------dict_keys(['Uno', 'Dos', 'Tres'])
Tres

VALUES

Specify the value associated with the pair.

print(D.values())
print(list(D.values())[1])
--------------------------------------------------------------------dict_values([1, 2, 3])
2

POP

Similar to a list, ‘pop’ can enable us to remove a specified key (inside standard parentheses as shown below). It reads very nicely.

D.pop('Uno')
print(D)
--------------------------------------------------------------------{'Dos': 2, 'Tres': 3}

As always, if you are new to dictionaries in Python the best way is to start playing around with examples and implement them into a larger program.

If you want a refresher on lists, click here.

--

--