Dictionary
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).
Read this built-in: dict article from Real Python and pay special attention to sections dict Operators and dict Methods.
Remember, just read through, you do not have to know it all.
Exercise
Complete [TODO] Exercise 08 — WorkingTitle to practice dictionaries.
Assignment
In this assignment, we will completely eliminate list index tracking by refactoring our inventory into a dictionary, mapping each product name directly to its price and stock.
- Open
main.pyin our project directory. - Replace
inventorylist with an empty dictionary{}. - When reading users input, assign the item directly to dictionary
inventory.inventory[name] = {"price": price, "stock": stock} - In customer order, look up if item is in the inventory directly with
if item_name in inventory, verify stock availability withinventory[item_name]["stock"]and update stock count in place withinventory[item_name]["stock"] -= 1and if stock reaches0then delete the item from the inventory usingdel inventory[item_name]. - Keep
orderas a list of tuples, and update theunsold_itemsvariable to check between keys of the dictionary and tuple elements - useinventory.keys()to get a tuple-like object of dictionary keys that you can use in this case to substractorderelements from keys of dictionary. - Test your application, make sure it works, commit and push to Github.
What's Next
We are now done with basic data structures in Python, next we move on to something even more fun and useful, kind of a super power in Python: coprehensions