Simplifying code with defaultdict in python

Опубликовано: 27 Сентябрь 2023
на канале: DigitalSreeni
2,977
118

Tips and Tricks 52​ : Simplifying code with defaultdict in python

Code from this video is available here: https://github.com/bnsreenu/python_fo...

Simplifying Code with defaultdict

You start with an empty notebook, and you want to add three types of fruits:
apples, bananas, and cherries.

To do this, you open the notebook and look for the page for "apples."
But the notebook is empty, so there's no page for "apples."

You have to create a page for "apples" first and write down that you have 2 apples.

Next, you want to add bananas. You look for the page for "bananas,"
but it's not there, so you create a new page for "bananas" and write down that you have 1 banana.

You repeat this process for cherries, creating a page for them and writing
that you have 3 cherries.

Now, imagine someone asks you, "How many dates do you have?" You try to look for a "dates" page in your notebook, but it doesn't exist.

You have to be careful not to make mistakes and accidentally forget to create a page for any fruit or forget to update the count correctly.
This manual checking and updating make your notebook longer and more error-prone.

The need for defaultdict:

You start with a magical notebook (a defaultdict) that automatically creates a page for any fruit you mention.

You confidently write down the counts of your fruits without worrying if the
pages exist or not. For example, you just say, "I have 2 apples," and the notebook creates an "apples" page for you if it doesn't already exist.

You add bananas and cherries the same way, without needing to manually check or create pages.

Now, when someone asks about dates, you confidently check the "dates" page in your notebook. If it doesn't exist, the notebook kindly tells you that you have 0 dates.

Your magical notebook simplifies your record-keeping. You don't have to write extra code to handle missing pages or worry about making mistakes, making your record-keeping shorter and more accurate.


На этой странице сайта вы можете посмотреть видео онлайн Simplifying code with defaultdict in python длительностью часов минут секунд в хорошем качестве, которое загрузил пользователь DigitalSreeni 27 Сентябрь 2023, поделитесь ссылкой с друзьями и знакомыми, на youtube это видео уже посмотрели 2,977 раз и оно понравилось 118 зрителям. Приятного просмотра!