Python Lesson 10: Nested Sets & Dictionaries

Advertisements

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

 

 

 

 

 

 

 

Leave a ReplyCancel reply