Dictionary
Introduction
Dictionaries in Python are mutable and unordered collection data structure. Mutable meaning it can be modified after creating and unordered meaning it does not keep track of it's elements.
Dictionaries are something special, usually called key-value data structure because of the way you store data inside them. You will certanly do a lot of work involving dictionaries in your python applications and its a very powerful concept, so let's get started.
Lesson Overview
In this lesson you will learn:
- How to create a dictionary
- How to manipulate elements
- How to iterate over dict
Dictionary
Creating Dictionary
We create a dictionary in Python using curly braces {}. It consists of two values; key and value. Key is what you use to access the element and value is what that element holds.
Let's see an example:
Keys can be any imutable type like strings, integers, floats, tuples, etc...
Values can be practicly anything, from simple strings and numbers to complex lists, other dictionaries or any combinations which you want and need.
To separate elements (key-value pairs), use comma ,.
Accessing Elements
Accessing an element in a dictionary is done with [] syntax but unlike indexes we used before, now we use key of the element to retrive it.
If the key does not exists, Python will raise KeyError. We can get around that by using .get() method which is safer to use as it does not raise an error, but returns None (by default) if the key does not exists.
Updating Elements
Updating elements is as simple as assigment of a new value to existing key.
Adding Elements
Adding new elements to dictionary is done just like updating but we use key that is not already in the dictionary.
Removing Elements
To remove and return the value of the element from dictionary you can use .pop() method which takes in a single argument; key.
You can also use delkeyword to remove a key-value pair from the dictionary.
For clearing the whole dictionary content you can use .clear() method.
Iterating Over Elements
Its common to iterate over dictionaries to check if it contains some specific values or simply using elements one by one. Dictionaries have two methods that help with this.
Let's go over what happens when you iterate over a dictionary by itself.
We would expect to get both keys and values, but you can see, that is not the case. This only returnes keys present in the dictionary.
You can also use .keys() method to get the same result.
While it can be useful, we usually want to grab values, or both keys and values. To grab just values contained we can use .values() method which does exactly that.
To grab both keys and values, we can use .items() method. This method returnes 2 values which we can unpack directly to key and value pairs (these are just variables, so you can name them whatever you want).