Beginners Guide to Python, Part2: Dictionaries

Niall McNulty
May 1, 2020 · 7 min read

Not to be mistaken for the Oxford Dictionary….

Photo by Aaron Burden on Unsplash

Welcome back! I hope you found ‘Beginners Guide to Python, Part1: Lists’ insightful. Even if it only helped a tiny bit, that’s still a win for me! My goal is to help and encourage you on your Python and machine learning journey. It wasn’t too long ago that I was an absolute nooooob at coding. I still consider myself a novice, but with persistence and even 30 minutes a day, you’ll start to see progress.

In our ‘Beginners Guide to Python, Part2: Dictionaries’, we will explore how to use and manipulate Python dictionaries. Dictionaries are a slightly more difficult concept to grasp, but I’m sure we can go from noob to pro in no time!

Just as real dictionaries have a definition assigned to a word, in Python we assign a value to a key {Key : Value}. Dictionaries are enclosed in ‘squiggly’ brackets as shown above, with a colon separating our value and key. Looking back to, ‘Beginners Guide to Python, Part1: Lists’ we know this is called syntax!

We could for instance use a dictionary to associate a location with a zip/postcode. You could assign your friends as keys and their phone numbers as values.

Note: Dictionary keys and values are not limited to just strings and integers. Values can be any type of object (including a dictionary — this is called a nested dictionary — we will touch upon this at a later stage), but keys must be immutable (cannot be altered). This means keys could be integers, strings, or tuples, but not lists, because lists are mutable. Dictionaries themselves are mutable, as you can add or delete from them.

Creating a Dictionary

Lets get started (加油)! First we need to create a dictionary and assign it to a variable.

The most basic way of creating a dictionary is to manually type one up! Although this could become tedious if we have a lot to input. Luckily for us today, we’re only adding a few {key:values}.

The dictionary below has my family members as keys and their ages for values. It helps me remember….oops

I’ve also assigned it to the variable name mix, however you can make it whatever you want.

mix = {}
>>> {}mix = {'Mum' : 55, 'Dad' : 56, 'Brother' : 33, 'Sister' : 28, 'Grandma' : 89}
>>> {'Mum' : 55, 'Dad' : 56, 'Brother' : 33, 'Sister' : 28, 'Grandma' : 89}

We can also make a dictionary with the dict() function.

mix = dict(Mum=55, Dad=56, Brother=33, Sister=28, Grandma=89)
>>> {'Mum': 55, 'Dad': 56, 'Brother': 33, 'Sister': 28,
'Grandma' : 89}

The next method, is slightly more complicated, but I thought it would be useful to include. Its when you zip() two lists together.

family_members = ['Mum', 'Dad', 'Brother', 'Sister', 'Grandma']
age = [55, 56, 33, 28, 89]
mix = dict(zip(family_members, age))
>>> {'Mum': 55, 'Dad': 56, 'Brother': 33, 'Sister': 28,
'Grandma' : 89}

zip() iterates through both lists and pairs them up by index and turns them into tuples. We can then use the dict() operator to turn the tuples into {keys:values}.

Remember — always play around with the code and get familiar with it. When I first started I always forgot to close a bracket ) or put a comma , somewhere. Its no good just reading articles, you need to practice so it commits to muscle memory.

Accessing Values of Keys

Values for a key can be accessed using the square bracket [ ] syntax and the .get() method.

Lets say we want to .get() the value assigned to Grandma. Its her birthday soon and I need to remember how old she is! Just like ‘Beginners Guide to Python, Part1: Lists’, the output will proceed >>>

mix.get('Grandma')>>> 89

One potentially confusing aspect of dictionaries is that although they are created with the curly brackets { }accessing a value with a key can be done using square brackets [ ].

mix['Grandma']>>> 89

Removing Elements from our Dictionaries

Just like lists, we can use the .pop() and del my_dict[]method to remove elements from our dictionaries. .pop() returns the value, which we can then assign to a variable if we so choose. Unlike lists where the default for .pop() would pop the last element of our list, with dictionaries you need to state a parameter. The parameter being a specific key.

gran_age = mix.pop('Grandma')
>>> 89mix.pop('Grandma')>>> 89

If however, we do want to pop the last element of our dictionary, we would use .popitem() and this would remove the last element from our dictionary and return a tuple with the key and value. We can assign it to a variable if we need to, as shown below.

gran_age = mix.popitem()
>>> ('Grandma', 89)mix.popitem()>>> ('Grandma', 89)

del my_dict[] can also be used just like with our lists. Lets have a quick review of how to use this.

del mix['Grandma']

Hold up! Lets double check that the {‘Grandma’ : 89} key and value has been removed from our dictionaries! 👍 👍

print(mix)>>> {'Mum': 55, 'Dad': 56, 'Brother': 33, 'Sister': 28}

Returning a List

Now lets say we want a list of all the keys in our dictionary or a list of tuples showing every key and value (refer to Beginners Guide to Python, Part1: Lists’ for definition of a tuple). We could use the .keys() .items() and .values()methods.

  • keys() returns a list of the keys.
  • Items() returns a list of tuples containing the keys and values.
  • values() returns a list of the values.
mix.keys()>>> dict_keys(['Mum', 'Dad', 'Brother', 'Sister'])list(mix.keys())>>> ['Mum', 'Dad', 'Brother', 'Sister']mix.items()>>> dict_items([('Mum', 55), ('Dad', 56), ('Brother', 33), ('Sister', 28)])list(mix.items())>>> [('Mum', 55), ('Dad', 56), ('Brother', 33), ('Sister', 28)]mix.values()>>> dict_values([55, 56, 33, 28])list(mix.values())>>> [55, 56, 33, 28]

Capeesh? Great, lets move on and master the basics of modifying our dictionaries. Note: Remember that Grandma has been removed from our dictionary.

Modifying Dictionaries

Now this got me thinking…. How old is my Grandpa? I’m not even sure if he’s in my massive dictionary. We can check with the following code snippet.

 'Grandpa' in mix >> False

Guess not! Now obviously this would be more useful when our dictionaries are quite long and we don’t want to search manually. Coding is all about making things fast, efficient and automated. Anyhoo, lets get modifying!

Adding new key:value pairs to a dictionary is similar to how you access an existing entry. The syntax for adding a new entry is: my_dict['new_key'] = new_value.

mix['Grandpa'] = 101
>>> {'Mum': 55, 'Dad': 56, 'Brother': 33, 'Sister': 28, 'Grandpa': 101}

We can also add new entries into our dictionary by using the .update() method. I guess I could add my dog to the list!

mix.update({'Theo' : 3})
>>> {'Mum': 55, 'Dad': 56, 'Brother': 33, 'Sister': 28, 'Grandpa' : 101, 'Theo': 3}

Keep in mind the syntax and parameters for each of our methods and functions. If you are using Jupyter Notebook, hold shift and tab inside the () to get the docstring. The docstring simply describes what the function/method does and its parameters. It can be very useful!

There is one more method we can use to modify or access our dictionaries. It’s called the .setdefault() method. We can either return an existing value, as such..

mix.setdefault('Dad')>>> 56

Or we can add a new entry into our dictionaries, as such..

mix.setdefaut('Auntie', 51)
>>> {'Mum': 55, 'Dad': 56, 'Brother': 33, 'Sister': 28, 'Grandpa': 101, 'Theo': 3, 'Auntie': 51}

Good work everyone. That just about does it! Before we call it, lets clear out our dictionary of all its keys and values. We can do this with….. you guessed it! .clear()

>>> {}

To Conclude

  • use .pop(key) to remove a {key:value} pair from the dictionary and return the value
  • use .get(key) to get the value for a key
  • use my_key in my_dictionary to check if a key my_key is in the dictionary my_dictionary
  • use .keys() to get a list of the keys in the dictionary
  • use .items() to get a list of the key:value pairs in the dictionary
  • use .update(other_dictionary) to merge a second dictionary into the current dictionary
  • use .clear() to remove all key:value pairs from the dictionary
  • use del my_dict[key] to remove a key-value pair from the dictionary

That ends things for todays ‘Beginners Guide to Python, Part2: Dictionaries’. I hope this reaches people and is a useful tool for some beginners or noobs out there. If anyone has any question, comments or constructive criticism, feel free to message in the comments. I will get back to you! Next week I’ll post ‘Beginners Guide to Python, Part3: For Loops’! Dun dun dun! I found these quite tricky when I was first starting out with Python, so I will try and go through it as clearly as possible!

Take care and stay healthy. Until next time, goodbye!

The Startup

Get smarter at building your thing. Join The Startup’s +800K followers.

Niall McNulty

Written by

I’m a junior data scientist who enjoys long-distance running, football, travelling, reading, food, programming… the list could go on. Never stop learning!

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +800K followers.

Niall McNulty

Written by

I’m a junior data scientist who enjoys long-distance running, football, travelling, reading, food, programming… the list could go on. Never stop learning!

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +800K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store