17.5. πŸ‘©β€πŸ’» Structuring Nested DataΒΆ

When constructing your own nested data, it is a good idea to keep the structure consistent across each level. For example, if you have a list of dictionaries, then each dictionary should have the same structure, meaning the same keys and the same type of value associated with a particular key in all the dictionaries. The reason for this is because any deviation in the structure that is used will require extra code to handle those special cases. The more the structure deviates, the more you will have to use special cases.

For example, let’s reconsider this nested iteration, but suppose not all the items in the outer list are lists.

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

Now the nested iteration fails.

We can solve this with special casing, a conditional that checks the type.

You can imagine how many special case if-thens we’d need, and how complicated the code would get, if we had many layers of nesting but not always a consistent structure.

You have attempted 1 of 3 activities on this page