Python Lesson 10: Nested Sets & Dictionaries

Hello everybody,

It’s Michael, and here’s my 10th Python lesson on nested sets & dictionaries (which serves as a direct continuation of my 9th Python lesson on nested lists & tuples).

So, what can you do with a nested set? First of all, let’s take a look at a nested set:

set1 = {“Colts”, “Chargers”, “Dolphins”, {“Browns”, “Ravens”, “Steelers”},
“Raiders”, “Titans”, “Patriots”}

However, when I try to print this set out, an error message pops up instead. Take a look:

TypeError: unhashable type: ‘set’

Now, why could this be? After all, nested lists and tuples worked just fine. Here’s the thing-since sets are immutable (meaning that they cannot be changed), they cannot contain any mutable (or changeable) elements, which include other sets.

OK, so even though you can’t make a nested set, you can certainly make a nested dictionary and do everything with it that you could do with a normal dictionary.

Here’s what a nested dictionary looks like:

cartoons = {“show1” : {“name” : “Rick and Morty”, “debut”: 2013},
“show2” : {“name” : “South Park”, “debut” : 1997},
“show3” : {“name” : “The Simpsons”, “debut” : 1989},
“show4” : {“name” : “Bob’s Burgers”, “debut” : 2011},
“show5” : {“name” : “American Dad”, “debut” : 2005}}

As you can see, a nested dictionary contains several dictionaries-within-dictionaries, each with their own keys and values.

Now, you can do the same things with nested dictionaries that you can with regular dictionaries, such as:

…accessing certain items from the dictionary (it’s not feasible to do negative indexing or to select a range of elements):

print(cartoons[“show3”][“debut”])

1989

In order to select an item in a nested dictionary, first select the name of the outermost dictionary –show3 in this case-to use as the first index (remember to put the name of the dictionary in quotation marks). Then select the name of any of the keys in the innermost dictionary-I chose the debut key in this case. The element returned is 1989-the year The Simpsons debuted on FOX.

  • If you have more than two layers of dictionaries, you would use the name of the dictionary for each index but the last; for the last index (which wo`uld represent the innermost dictionary), use the name of the key you want to access.

…add an item to the dictionary:

cartoons[“show1”][“seasons”] = 4

print(cartoons)

{‘show1’: {‘name’: ‘Rick and Morty’, ‘debut’: 2013, ‘seasons’: 4}, ‘show2’: {‘name’: ‘South Park’, ‘debut’: 1997}, ‘show3’: {‘name’: ‘The Simpsons’, ‘debut’: 1989}, ‘show4’: {‘name’: “Bob’s Burgers”, ‘debut’: 2011}, ‘show5’: {‘name’: ‘American Dad’, ‘debut’: 2005}}

To add an item to a nested dictionary, first mention the name of the main dictionary (cartoons in this case), then mention the name of the outermost dictionary and use that as the first index. Since there are five outermost dictionaries (show1, show2, show3, show4, show5), you can only select one of them as the location to add the element (I chose show1). Next, you should create a new key for the dictionary and assign a value to that key (I added the key seasons and the corresponding value of 4).

  • Yes, when you add an element to a nested dictionary, you need to add both a key and a corresponding value.
  • If you have more than two layers of dictionaries, you must keep using the dictionary names as indexes until you reach the innermost layer, at which point you can create the key-value pair.

…add a whole dictionary-within-a-dictionary:

cartoons[“show6”] = {“name” : “Bojack Horseman”, “debut” : 2014}

print(cartoons)

{‘show1’: {‘name’: ‘Rick and Morty’, ‘debut’: 2013}, ‘show2’: {‘name’: ‘South Park’, ‘debut’: 1997}, ‘show3’: {‘name’: ‘The Simpsons’, ‘debut’: 1989}, ‘show4’: {‘name’: “Bob’s Burgers”, ‘debut’: 2011}, ‘show5’: {‘name’: ‘American Dad’, ‘debut’: 2005}, ‘show6’: {‘name’: ‘Bojack Horseman’, ‘debut’: 2014}}

Yes, you can add a whole dictionary-within-a-dictionary to a nested dictionary. To do so, you would simply mention the name of the main dictionary (cartoons) and mention a new name for the new dictionary that you will use as the first index (I used the name show6).

  • If you have more than two layers of dictionaries, you would need to include additional indexes until you reach the innermost layer, at which point you can create the new dictionary. Remember to include a few key-value pairs in the new dictionary.

…remove an element from the dictionary:

del cartoons[“show1”][“seasons”]

print(cartoons)

‘South Park’, ‘debut’: 1997}, ‘show3’: {‘name’: ‘The Simpsons’, ‘debut’: 1989}, ‘show4’: {‘name’: “Bob’s Burgers”, ‘debut’: 2011}, ‘show5’: {‘name’: ‘American Dad’, ‘debut’: 2005}, ‘show6’: {‘name’: ‘Bojack Horseman’, ‘debut’: 2014}}

To remove an element from a nested dictionary, first mention the keyword del. Then mention the name of the main dictionary followed by the name of the outermost dictionary where the element you wish to remove is located. Then (provided you only have two layers of dictionaries), you would mention the name of the key inside that dictionary that you wish to remove (I chose the seasons key).

  • If you’re trying to remove an element from a nested dictionary, don’t worry about including the value. By simply including the key (along with corresponding layers of dictionaries), Python will know what value to delete.

 

…deleting a whole dictionary-within-a-dictionary (if you can add entire dictionaries, it makes sense that you can delete them too):

del cartoons[“show6”]
print(cartoons)

{‘show1’: {‘name’: ‘Rick and Morty’, ‘debut’: 2013} , ‘show2’: {‘name’: ‘South Park’, ‘debut’: 1997}, ‘show3’: {‘name’: ‘The Simpsons’, ‘debut’: 1989}, ‘show4’: {‘name’: “Bob’s Burgers”, ‘debut’: 2011}, ‘show5’: {‘name’: ‘American Dad’, ‘debut’: 2005}}

Deleting whole dictionaries-within-dictionaries is quite simple-just use the keyword del followed by the name of the main dictionary and the dictionary-within-a-dictionary you wish to delete (in this case, I chose to delete show6).

…loop through a dictionary

for c_id, c_info in cartoons.items():
print(“\nShow ID:”, c_id)

for key in c_info:
print(key + ‘:’, c_info[key])

Show ID: show1
name: Rick and Morty
debut: 2013
seasons: 4

Show ID: show2
name: South Park
debut: 1997

Show ID: show3
name: The Simpsons
debut: 1989

Show ID: show4
name: Bob’s Burgers
debut: 2011

Show ID: show5
name: American Dad
debut: 2005

Iterating though a nested dictionary (or a regular dictionary for that matter) is different than iterating through a list, set, or tuple. This is because dictionaries have key-value pairs, so therefore you need to iterate through the keys AND the values.

In the first block of the loop (the first two lines), Python is iterating through all of the names of the outermost dictionaries (the dictionaries that start with show) and writing Show ID before the name of each of the show dictionaries.

  • The \n is an escape character; this tells Python to skip to a new line after for each Show ID (and any corresponding key-value pairs)

In the second block of the loop (the last two lines), Python is iterating through all of the key-value pairs in the dictionary. The print statement in this block will print out all of the key-value pairs in the entire dictionary.

  • Even though I removed the seasons key in a previous example, it still pops up here. Perhaps Python still thought the seasons key was present. Interestingly, the show6 dictionary wasn’t displayed.

 

…and last but not least, let’s see how we can find the length of a nested dictionary:

print(len(cartoons))

5

So, why would it be 5? Why wouldn’t it be 10, since there are two key-value pairs per outermost dictionary?

The length of cartoons would be 5 since there are 5 outermost dictionaries, and len counts the amount of outermost dictionaries in this case.

Thanks for reading,

Michael

 

 

 

 

 

 

 

Python Lesson 8: Sets & Dictionaries

Hello everybody,

Michael here, and today’s post will cover sets and dictionaries in Python. In the last post I covered lists and tuples, which are two of the four major types of collections in Python (sets and dictionaries being the other two).

First off, let’s discuss sets. Sets are collections of items that are unordered and unindexed:

Let’s take an example of a set:

Screen Shot 2020-03-02 at 9.12.38 PM

This is a set of random years. Sets are written in curly brackets (on the other hand, tuples are written in round brackets and lists are written in square brackets).

Now, let’s see how we can access an item in a set:

Screen Shot 2020-03-02 at 9.19.56 PM

So how can we access items in a set? Well, we can’t. After all, since sets are unindexed, you can’t call a certain index like you can with lists and tuples.

However, you can loop through all the items in a set with a for loop:

Screen Shot 2020-03-03 at 11.28.31 AM

You can also check to see if a certain item is present in a set:

Screen Shot 2020-03-03 at 11.33.39 AM

Ok, so checking to see if an item is in a set isn’t the same process as it would be for a tuple or list. It’s also a lot simpler (just taking one line) and doesn’t print out a message. Rather, True would be printed if the specific item is in the set, and False would be printed if the specific item isn’t in the set.

Now what should we do if we want to add an item to a set? Granted, you can’t change items in a set, but you can certainly add and remove items in a set. Here’s how you would add items to a set:

Screen Shot 2020-03-03 at 11.57.07 AM

As you can see, there are two possible methods for adding items to a set-add and update. The only difference between these two methods is that you would use add if you only wanted to add one item and update if you wanted to add several items.

You also likely noticed that the parameter I used for add is an int, but the parameters I used for update are String. This is because the update method won’t work with integers, so I had to make the years String. One thing I didn’t realize would happen when I did this was that all of the individual digits from each String were going to be printed as separate elements (and that no two digits would be repeated). Hey, even someone as programming-savvy as myself learns new coding caveats each time.

Now let’s try and remove an item from the set:

Screen Shot 2020-03-03 at 12.19.10 PM

Just as there are two methods for adding an item to a set, there are also two methods for removing items from a set-remove and discard. Unlike the two methods for adding items, these methods are interchangeable. The only difference between these two methods is that remove will raise an error if the item you’re trying to remove doesn’t exist-discard will not.

You can also use the pop method to remove an item from a set:

Screen Shot 2020-03-03 at 12.31.04 PM

Keep in mind that even though pop removes the last item from the set, sets are unordered, so you’re not going to know which item is going to be removed until you print out the list after using pop.

If you wanted to clear a set, use clear name_of_set. If you wanted to delete an entire set, use del name_of_set.

Now, let’s take a look at joining sets. Here’s an example as to how to do that:

Screen Shot 2020-03-03 at 2.57.40 PM

First of all, I made a new set yearset2 (I needed to make a new set in order to have something to join my current set to). I then used the union method to join the two sets together and stored the new joined set as a new variable called years, which I then printed out.

Another way I could’ve joined yearset and yearset2 was with the update method; I could’ve written yearset.update(yearset2)and that would’ve accomplished the same thing as using the union method.

  • The union and update methods both omit duplicates.

Last but not least, let’s check the length of the set (using yearset):

Screen Shot 2020-03-03 at 3.13.40 PM

Now that I’ve covered everything about sets, let me move on to dictionaries. Dictionaries are collections of items that are unordered, changeable, and indexed. They are written with curly brackets and have keys and values. Here’s an example of a dictionary:

Screen Shot 2020-03-03 at 8.07.16 PM

The keys (country, state, and city) are to the left of the colon while the values (United States, Tennessee, and Nashville) are to the right of the colon. The keys don’t need to be String, but if you want to use words as keys, then you must put them in double quotes.

  • It might help to think of a Python dictionary like an actual dictionary, where the keys are the words and the values are the definitions.

So, how can we access the items of a dictionary? (It’s not the same way you would access the items of a set, list, or tuple):

Screen Shot 2020-03-04 at 10.22.32 PM

 

These are two examples of incorrect ways to access elements in dictionaries. The first example is incorrect because Tennessee is a value, not a key, and you can’t try to access elements in a dictionary by directly calling values. The second example is incorrect because you can’t call an index in a dictionary like you can with a list, set, or tuple (though I might add that the second example would be correct if you had 2 as a key).

Here’s the correct way to access items in dictionaries:

Screen Shot 2020-03-04 at 10.35.40 PM

The only way to access items in dictionaries is by calling the key. Remember to put the name of the key in full quotes if the key is a String.

  • I could’ve also used the get method, typed dict1.get(country) into Jupyter notebook, and gotten the same result.

So, now let’s change the values of this dictionary:

Screen Shot 2020-03-04 at 10.45.41 PM

In this example, I changed city to Miami Springs and state to Florida​, then printed out the resulting dictionary. To change an element in a dictionary, use the syntax dictionary name[key name] = new value for that key.

You can also loop through the elements of a dictionary, just as you can loop through the elements of a list, set, or tuple. Here’s how to loop through the elements of a dictionary:

Screen Shot 2020-03-05 at 10.25.13 PM

So while this loop did iterate through the elements of this dictionary, it only returned the keys of the dictionary, not the values. If you want to return the values of this dictionary, here are two ways to so:

Screen Shot 2020-03-05 at 10.33.58 PM

In the first example, you would use the syntax print(dictionary name[x*]) to print out all of the values of the dictionary. In the second example, you would use the values method and the syntax dictionary name.values() to print out the values of the dictionary.

  • *Use whatever letter you have after for in place of x

If you want to loop through both the keys and values of a dictionary (and print them both), use the items method:

Screen Shot 2020-03-05 at 10.43.23 PM

Now let’s see how we can check to see if an item is in a dictionary:

Screen Shot 2020-03-07 at 2.40.09 PM

In this example, I am checking to see if the key state is in dict1 and if it is, I will print out the message State is in this dictionary (this is exactly what happened here).

Interestingly, this same approach doesn’t work when you want to check if a certain value is in a dictionary (recall that Tennessee was one of the original values in the dictionary). Not quite sure why this is the case:

Screen Shot 2020-03-07 at 2.47.00 PM

Now, how would we add a new element to our dictionary? Here’s how:

Screen Shot 2020-03-07 at 2.53.31 PM

Since dictionaries have two elements-a key and a value-you need to create a new key as well as a new value if you want to add an element to the dictionary.

Now, let’s see what we should do if we want to remove an element from the dictionary:

Screen Shot 2020-03-07 at 2.58.05 PM

Just as with lists, sets, and tuples, you can use the pop method on a dictionary to remove an item.

However, there is also a method called popitem, which will remove the last key-value pair in the dictionary (unless you’re using a Python version before 3.7, in which case a random item will be removed instead):

Screen Shot 2020-03-07 at 3.04.12 PM

If you wanted to remove more than just a single key-value pair, the del and clear methods are just what you would want. Del would delete a dictionary completely, while clear would simply empty the dictionary without deleting it.

  • An important caveat to note is that you could also use del to remove a key-value pair in a dictionary (along with being able to delete a dictionary completely).

 

Now, what should we do if we want to make a copy of our dictionary (keep in mind I added back the elements I had previously removed):

Screen Shot 2020-03-07 at 3.13.31 PM

First of all, simply writing dict2 = dict1 wouldn’t work because dict2 would simply be a reference to dict1, rather than a copy of dict1. In order to create a copy of a dictionary, use the copy method.

You could also use the dict method with the syntax name of new dictionary = dict(name of current dictionary) to copy your current dictionary.

Last but not least, let’s see how we can check the length of our dictionary:

Screen Shot 2020-03-07 at 3.18.43 PM

You would use the len method to check the length of a dictionary, just as you would when you want to check the length of a tuple, list, or set. But why is len 4 and not 8? This is because key-value pairs are counted as one item, and since there are 4 key-value pairs, len is 4.

Thanks for reading,

Michael