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 9: Nested Lists and Tuples

Hello everybody,

It’s Michael, and today’s post will be about nesting. This post will involve lists, tuples, sets, and dictionaries, but it won’t necessarily be a continuation of my last two Python posts. In this post, I’ll be demonstrating nested and tuples (with the next post covering nested sets and dictionaries).

First I will demonstrate a nested list (think of this as a list-within-a-list):

fruitsandveggies = [‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’,], ‘apples’
, ‘strawberries’]

And here’s some sample output (based on me choosing a specific element from the nested list):

print(fruitsandveggies[2][1])

celery

In this example, I have the nested list fruitsandveggies and have selected element [2][1] from the list. However, you’re probably wondering what element I’m referring to when I say [2][1]. In this list, [2] refers to the outermost list while [1] refers to the innermost list. So when I want to pick element [2][1] from the fruitsandveggies list, I’m saying that I want to pick index 2 (the 3rd item) from the outermost list and index 1 (the 2nd item) from the innermost list (the corresponding element is celery).

So whenever you see something like fruitsandveggies[2][1], remember that the first index ([2] in this case) represents the outermost list and any subsequent indexes represent lists that are further inward. In this example, [1] would represent a list that is further inward. Had I included more nested lists, any subsequent indexes would’ve represented lists that were further inward. The last index listed would represent the innermost list.

So remember that when you see something like list name[a][b][c][d][e], remember that the first index listed (represented by [a]) would represent the main list. Any subsequent indexes (represented by [b], [c], and [d])  represent lists that are further inward, while the last index (represented by [e])  represents the innermost list.

  • Helpful tip-when you are selecting an element from a nested list, remember to choose an index with a nested list! For instance, a statement like print(fruitsandveggies[3][1])​  wouldn’t have worked because index 3 (the 4th item in the outermost list) doesn’t contain a nested list.

You can also do many of the same things with nested lists that you can with normal lists, such as:

…negative indexing

fruitsandveggies = [‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’
, ‘strawberries’]

print(fruitsandveggies[-3][-1])

zucchini

Remember that the negative indexing rules that apply for regular lists also apply for nested lists (e.g. first index in negative indexing is -1, not 0)

…adding items to the list (using the same methods you would use for regular lists)

fruitsandveggies.append(‘grapefruit’)
fruitsandveggies.insert(2, ‘squash’)

print(fruitsandveggies)

[‘bananas’, ‘oranges’, ‘squash’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’, ‘grapefruit’]

In this example, I used append to add the item grapefruit to the list and insert to add squash to the list.

When using these methods with nested lists, keep in mind that the appended item will be added to the outermost list, not any nested lists. Also keep in mind that when you use the insert method in a nested list, the index you want to place the element in corresponds to the outermost list, not any nested lists. In this example, I wanted to insert the element squash at index 2; this means that squash would be inserted at index 2 OF THE OUTERMOST LIST.

…removing items from the list (using the same methods that work for normal lists):

fruitsandveggies.pop()
del fruitsandveggies[2][1]

print(fruitsandveggies)

[‘bananas’, ‘oranges’, [‘peppers’, ‘zucchini’], ‘apples’]

In this example, I used the pop and del methods to remove items from the list fruitsandveggies. Pop removed the last item from this list; however, it might have removed a different element had I specified an element to remove. Del removed the item from this last that was located at the index I specified- [2][1] (meaning that the item at index 1 of the nested list was removed).

…finding the length of a list:

fruitsandveggies = [‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’
, ‘strawberries’]

print(len(fruitsandveggies[1]))
print(len(fruitsandveggies[2]))

7
3

Finding the length of a nested list is essentially the same as finding the length of a regular list (you would also use the len method), but include an index after the list name. The index will let Python know the list whose length you wish to find. For instance, if you use the index [1], you will get the length of the entire list (which in this case is 7). However, if you were to use the index [2], you would get the length of the nested list (which in this case is 3) . If I had more nested lists in this example,  I would use indexes such as [3], [4], [5], and so on, depending on how far inward the lists were located.

Last but not least, let’s see how we can iterate through the elements of a nested list:

for list in fruitsandveggies:
for i in list:
print(fruitsandveggies)

[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]
[‘bananas’, ‘oranges’, [‘peppers’, ‘celery’, ‘zucchini’], ‘apples’, ‘strawberries’]

In this example, I iterated through this nested list with a nested for loop. One thing I didn’t realize when I created this loop was that the list was going to be printed 21 times (I’m guessing it’s 21 times because there are 7 elements in the main list while there are three elements in the nested list, so 7 * 3 = 21).

Next, I will demonstrate nested tuples. But first, let me show you how to create a nested tuple, as the process isn’t as simple as the one for creating a nested list:

tuple1 = (1, 3, 5, 7, 9)
tuple2 = (0, 2, 4, 6, 8)
tuple3 = tuple1, tuple2
print(tuple3)

((1, 3, 5, 7, 9), (0, 2, 4, 6, 8))

See, with a nested list, all you would need to do is write a list-within-a-list (or several lists-within-lists). On the other hand, with a nested tuple, you would actually need to create a new tuple that concatenates your other tuples, as I did in the above example (and yes, you can use a comma to concatenate your tuples. This is not Java).

Now, let’s say we wanted to access an item in our nested tuple. How do we do that?:

print(tuple3[1][1])

2

The process for accessing an item in a nested tuple is the same as it is for accessing an item in a nested list-use multiple indexes to get the element you want. However, the way indexes are counted in nested tuples differs from the index counting in nested lists, as individual tuples-within-the-tuple are counted as individual indexes. For instance, in tuple3, the first tuple (tuple1) counts as index 0 while the second tuple (tuple2) counts as index 1.

But what if I had only used a single index? Let’s see what would happen:

print(tuple3[1])

(0, 2, 4, 6, 8)

In this example, I used a single index-[1]-and got the entire second tuple as a result.

  • Remember that if you want to get a single tuple element, use multiple indexes. If you want to get a whole tuple, use a single index.

Negative indexing also works with nested tuples. Here’s an example (using both single and multiple indexes):

print(tuple3[-1])

(0, 2, 4, 6, 8)

print(tuple3[-1][-3])

4

How would we iterate through a nested tuple? We would basically use the same process we use to iterate through regular tuples:

for i in tuple3:
print(i)

(1, 3, 5, 7, 9)
(0, 2, 4, 6, 8)

Interestingly, the tuples printed out separately-by this I mean the tuples-within-the-tuple are displayed on separate lines rather than on the same line separated by a comma.

Now, how would we find the length of a nested tuple? Let’s find out:

print(len(tuple3))

2

How did I get 2 instead of 10? In this example, Python counted each individual tuple-tuple1 and tuple2-inside of my large tuple-tuple3-as an individual element. Since there are two tuples-within-the-tuple, len returned 2.

You may have noticed that I didn’t mention anything about adding or removing elements from nested tuples. This is because the methods that work for adding and removing items from regular tuples won’t work for nested tuples.

Thanks for reading,

Michael