Dictionaries are one of the most important, and widely used, data structures in Python. You can use them to store lists of strings, numbers, or even other dictionaries! In this guide, you’ll learn what they are and how to use them to your advantage in your Python projects.
Introduction: Defining a Dictionary
Dictionaries are one of Python’s handiest built-in data structures. In essence, they allow you to define your own key-value pairs using simple Python syntax. Unlike lists, dictionaries can contain values that are not numbers or strings; they may be any type of object such as a list, dictionary, string, integer, or boolean value. This makes them very powerful and flexible. Let's see how we can define the syntax of dictionaries in python,
dict = {<key1>:<value1>,<key2>:<value2>,<key3>:<value3>,...}
A dictionary mainly contains a key-value pair. The key is used to access its value. Each key is unique and cannot be repeated within a single dictionary. We can create dictionaries using curly braces {}. The values inside these curly braces are enclosed by either double or single quotes. If we want to add more than one value, then separate them with commas(,) as shown above: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}. If you have just one value, you don't need any quotes around it. For example, {'key1': 1} is also valid syntax for creating a dictionary in python.
Well, if the syntax doesn't look clear to you, let's see how a dictionary is actually implemented in python,
book = {"title":"Rich Dad Poor Dad","Author":"Robert Kiyosaki",}
Here we've created a dictionary called 'book' that contains the title and author as keys with its corresponding values.
Accessing Dictionary Values
In Python, a dictionary is an unordered collection of values, which are referenced using a key. The value associated with a key can be of any object type. If you want to retrieve a value based on its key, use square brackets: my_dict['key'], where my_dict is a dictionary instance.
Suppose you want to access the title and author name from the 'book' dictionary we have created, you can simply specify those keys inside the square brackets with the name of the dictionary just like this:
>>> book['title']Rich Dad Poor Dad>>> book['Author']Robert Kiyosaki
Now let's combine the results in one line,
book = {"title":"Rich Dad Poor Dad","Author":"Robert Kiyosaki",}title = book['title']author = book['Author']print("The book " + title + " is written by " + author)The book Rich Dad Poor Dad is written by Robert Kiyosaki
Just simple stuff, but what if you specified a key that is not present in the dictionary:
>>> book['year']Traceback (most recent call last): File "E:\Python Projects\twitterbot\test.py", line 6, in <module> date_published = book["date"] # Accessing the title of the book KeyError: 'year'
Python raises an exception when you try to access a key that doesn't exist in the dictionary.
Adding Key-Value pairs to a Dictionary
Now let's see how we can insert an element into a dictionary, So you are willing to add two more key-value pairs to our 'book' dictionary which are the year and month the book has been published. For doing that you need to create a new key and value pairs like this:
book['year'] = 1997book['month'] = "April"print(book){'title': 'Rich Dad Poor Dad', 'Author': 'Robert Kiyosaki', 'year': 1997, 'month': 'April'}
The new key-value pair will be added to the dictionary when running this code. Remember that dictionaries are unordered collections of data. That means that when you're adding new entries to your dictionary, you don't have to worry about inserting them into any particular order. In fact, you can't really insert them into any particular order!
Removing Key-Value pairs from a Dictionary
book = {"title":"Rich Dad Poor Dad","Author":"Robert Kiyosaki","year": 1997,"month":"April"}del book['year']print(book){'title': 'Rich Dad Poor Dad', 'Author': 'Robert Kiyosaki', 'month': 'April'}
As you can see that the key 'year' from the dictionary 'book' is being deleted. You don't need to specify the value in order to delete a particular key-value pair, the value and key together will be removed from the dictionary by only specifying the key. It’s important to note that you cannot delete a specific element from a dictionary using its position like we do in lists. It will throw a KeyError.
book = {"title":"Rich Dad Poor Dad","Author":"Robert Kiyosaki","year": 1997,"month":"April"}del book[1]Traceback (most recent call last): File "E:\Python Projects\twitterbot\test.py", line 8, in <module> del book[1] KeyError: 1
Modifying values in a Dictionary
book = {"title":"Rich Dad Poor Dad","Author":"Robert Kiyosaki","year": 1997,"month":"April"}book['title'] = "Harry Potter Philosopher's Stone"book['Author'] = "JK. Rowling"book['month'] = "June"print(book){'title': "Harry Potter Philosopher's Stone", 'Author': 'JK. Rowling', 'year': 1997, 'month': 'June'}
book = {"title":"Rich Dad Poor Dad","Author":"Robert Kiyosaki","year": 1997,"month":"April"}book.update({"title":"Harry Potter Philosopher's Stone","Author":"JK. Rowling","month":"June"})print(book){'title': "Harry Potter Philosopher's Stone", 'Author': 'JK. Rowling', 'year': 1997, 'month': 'June'}
Iterating Through a Dictionary
You can also loop through a dictionary by using the fancy for loop, which is much easier than writing out all of your keys. This will allow you to access each key-value pair as you iterate through it. One condition is that, when iterating through a dictionary, you’ll have to use two indices—one for accessing keys and one for accessing values. Here’s an example:
book = {"title":"Harry Potter Philosopher's Stone","Author":"J.K. Rowling","year": 1997,"month":"June"}for key, value in book.items():print("Key:",key, "\tvalue:", value)Key: title value: Harry Potter Philosopher's Stone Key: Author value: J.K. Rowling Key: year value: 1997 Key: month value: June
Here, there are two things to note, first is that we require two variables to access the key and value of the dictionary in the for loop, second is the item() method which is essential to retrieve a list of key-value pairs.
But can we access the key and value individually in a dictionary? yes, it's possible. You can individually loop through a key and value by using the keys() and values() method. Let's see how:
for key in book.keys():print(key)print("\n")for value in book.values():print(value)title Author year month Harry Potter Philosopher's Stone J.K. Rowling 1997 June
Nested Dictionaries
grades = {"James":{"Maths":90,"Science":97},"Sara":{"Maths":87,"Science":99}}
Accessing elements from the nested dictionary
james_grade_in_maths = grades['James']['Maths']saras_grade_in_science = grades['Sara']["Science"]print("James grade in maths:", james_grade_in_maths)print("Sara's grade in science:", saras_grade_in_science)James grade in maths: 90 Sara's grade in science: 99
Inserting elements to the nested dictionary
grades['James']["Average"] = (90 + 97)/2grades['Sara']['Average'] = (87 + 99)/2print("James average score:",grades['James']['Average'])print("Sara's average score:",grades['Sara']['Average'])James average score: 93.5 Sara's average score: 93.0
Iterating Through a Nested Dictionary
for names, subs in grades.items():print("\n",names)for sub, grade in grades[names].items():print(sub, grade)James Maths 90 Science 97 Sara Maths 87 Science 99
List inside a Dictionary
grades = {"James":[77, 90, 97, 68, 87],"Sara":[67, 99, 87, 70, 89]}sum = 0for key, grade_lists in grades.items(): # looping through the dictionaryfor i in grade_lists: # Looping through the listsum+=i # Finding the sum of all the elements in the listavg = sum/10 # finding the averageprint("The average of marks scored by James and Sara is:", avg)The average of marks scored by James and Sara is: 83.1
The dict() method
my_dict = dict(name="Sidharth", age=20)print(my_dict){'name': 'Sidharth', 'age': 20}