Advanced Dictionaries: defaultdict in Python
Key Takeaways
Utilizes Python's defaultdict for advanced dictionary operations
Full Transcript
what is going on guys welcome back in this video today we're going to learn about a somewhat more advanced data structure in Python called the default dig so the default dictionary we're going to discuss what it is how it works and when it could be useful so let us get right into it [Music] all right so we're going to learn about default dictionaries in Python today essentially just a data type that is very similar to a dictionary but with a Twist that we have default values so we can access key value pairs that don't exist yet so we don't have to always initialize the key value pair if we don't know what the value shall be because we can just use a default value or a missing value if you want to call it that so we can look at a very simple example here for example if I say my underscore dictionary equals just an empty dictionary this is how you initialize an empty dictionary or you can also just do it like this R so maybe let's do it like this because otherwise actually I'm not sure if this doesn't if I do it like this doesn't this actually initialize a set I think this might be actually wrong no it's actually a dictionary okay um anyway so this is how you initialize an ordinary python dictionary and what I can do now is I can print my dictionary you can see it's empty but if I go now and if I try to access a field that does not exist for example if I want to say name or something like this I'm going to get the exception here the error that I have a key error because name does not exist and the same goes of course if I try to do something like my Dix and then h and I want to increase H by 10 or something this won't work because we don't have the key H we don't have the key value pair where the key is H this changes when you use default dictionaries and in order to use default dictionaries you can just say from collections import default dict and then you can just say my dictionary here equals default dig and then we can pass here as a parameter the data type and depending on the data type that we pass we're going to have different default values different missing values if you want to call it that again and for example if I say int I can still print the dictionary and you're going to see it is an empty dictionary of class int you can see no data in it but the interesting thing is now if I go ahead and I say my dictionary h I'm going to get 0 as a result because um the the key is missing but the default dictionary assigns on demand just the default value to the field so the interesting thing is also if I now go ahead and print a dictionary we're going to get a different result because now I have actually this key value pair h0 and this also works of course if I increase something that does not exist so if I go ahead and say my dictionary some other value equals or not equals plus equals 20 then you're going to see that I now have this some other value being equal to 20 because the default value is zero on demand it is initialized and then I can just increase it by 20 and this solves the problem of constantly having to check for example I don't know maybe you want to keep track of some values maybe some score for person one uh has a score of zero person two has a score of zero and person three has a score of zero and then you want to say okay when something happens increase the score the problem is if you now introduce person four you would have to explicitly say that person four also is zero because if you go ahead now and you say something like values uh person for plus equals a score of 10 this is again going to lead to a problem because now of course you uh don't have the default value so you would have to turn this into a default dictionary uh then you don't need all this here then you can just get rid of all that and you can increase the score for person four which is going to initialize person four in the first place that is a very basic um demonstration of what default dig does now we can also go ahead and do something more useful for example we can use that for counting elements so let's say I have my list with a couple of values here something like this and then what we can do here is we can say counter equals default integer and then I can just say four elements in uh in my list I'm going to say counter for this particular element is going to be plus equal to one so very similar to what we did now with the Aging or with the with the score increase but you can see now that this works we don't have to initialize it as zero first we can just use it here um actually yeah I mean we can we can just go with element or we can go with sgr elements to keep it professional here this also works and you can see uh that this is the result another thing we can do is we can use a default dictionary for grouping stuff so if I have for example a list of words here let's say I have apple I have banana I have carrot I have avocado avocado I hope this is how it's pronounced uh broccoli and an orange if I have these words I can group them according to a certain to to some pattern so I can say here grouped words equals default dictionary with a type of list this time this is what we need to to group this here we can say four words in Words I can just say that the group words um we just want to append for the word um for the word zero basically meaning we take the first character so a b c a b o and we Group by this first character so for each first character in The List we're just going to append word and you notice here again if I print this group words we're using again append even though we don't have a list in the first place we don't create a list in the first place in an ordinary dictionary you would have to say Okay a is an empty list B is an empty list C is an empty list o is an empty list and of course because you don't know what's going to be part of the list you're going to have to do that for all letters from A to Z and this can be tedious this can be unnecessary now it's just creating on-demand empty lists for everything that we ask for and then we can also append stuff to that empty list without having to create that empty list in the first place that is a nice use case um and then also what I had to do recently this is actually very useful I had in a project that I was doing a tuple list so like this where I basically had a list of tuples so for example a and the value 10 or B and the value of 4. and a and the value 5. and then maybe C I think it was the result of some um some interesting some some art database select statement and I got these two posts and I wanted to group them I wanted to basically reduce them I wanted to um to aggregate them is the proper term so I wanted to combine a and a I want to combine B and B and then C in this case is the only C element here but I wanted to just say four plus one for example and to end up with a uh with with group data so it's essentially again grouping and what we can do here again is a quite similar Principle Group data equals default dictionary of list of type list and then four key value for every key value pair in this Tuple here in this Tuple list here we're going to say group data key append value same principle and then you have um basically uh you group the data and then you can also sum it up obviously so we can go and we can look at this so this would just group the data for example if you want to have a list of values but of course you can now go ahead and say okay sum everything up so we can say four maybe a dictionary comprehension maybe we can say group data equals and then a key and sum of V for KV in group data.items that should that should produce this so this is quite useful and the great thing is also that you can Define your own default dictionary so you can extend basically from this it has to be a class right yeah it's a class even though it's written in lower case um we can go ahead and say here my default dictionary extending from default dictionary and then I can just overwrite this double under method called missing and here we can just say self key equals value equals this is just a double assignment here saying that we're going to assign to self key and to Value the same value which is going to be the length of the key for example we can use this as an example so the default value for a value is going to be the length of the value so this is not just the same default value every time we now have something that is more Dynamic so I get a key like hello and hello has uh how many five characters so five characters would be um the integer five and five would then be the default value for hello if I say something else I'm going to get a different length and a different value so I'm going to just return value here um and we can test this out we're going to say test equals my default dictionary and then I can just print what the value is of test hello and you're going to see it's 5 because the word hello has a length of five if I say hi it's going to be 2 um and of course you can also see that this is then listed in the dictionary itself and you can do in this missing double under method whatever you want so you can say Okay I want to have the length I want to have a constant value it's also possible so self key equals value equals 10 then it's always going to be 10 no matter what you do or you can have some very Advanced logic in here the interesting thing is you can do all of this yourself and the last thing I want to show you here is we can also Define this as a Lambda expression or as a simple constant dictionary so if I want to say constant default dict or whatever you want to call it I can just say default dictionary and what I pass here is a Lambda expression or technically a function but a Lambda expression is a function and since it's so simple we don't need to have a fancy function for this but I can just say Lambda and then some value for example hello world uh and then if I use this dictionary I will have um so for example if I ask what is Hello the value of hello it's going to give me hello world because everything will have the default value hello world and of course you can also have some logic um or actually uh no you don't have a logic because this is a constant value but if you want to have a logic you can override the class and this is just a nice little useful thing because it's quite tedious as I mentioned in the beginning to have a dictionary where you want to keep track of stuff but you have a different case depending on whether you already encountered this object or not in the counting example or in the grouping example you know do you append or do you create an empty list because it's the first element so if I have um label label a here is this the first time I'm seeing label a and let's say the value associated with that is five so do I have to append five to an already existing list of values or do I have to create a new list with five in it this question is basically irrelevant once you have default dictionaries because then everything is treated equally you can just append and if it doesn't exist it's going to automatically create a new list and then append it to that new list so that's it for today's video I hope you enjoyed it and hope you learned something if so let me know by hitting a like button and leave a comment in the comment section down below and of course don't forget to subscribe to this Channel and hit the notification Bell to not miss a single future video for free other than thank you much for watching see you in the next video and bye
Original Description
Today we learn about defaultdict and advanced dictionaries in Python.
◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾
📚 Programming Books & Merch 📚
🐍 The Python Bible Book: https://www.neuralnine.com/books/
💻 The Algorithm Bible Book: https://www.neuralnine.com/books/
👕 Programming Merch: https://www.neuralnine.com/shop
🌐 Social Media & Contact 🌐
📱 Website: https://www.neuralnine.com/
📷 Instagram: https://www.instagram.com/neuralnine
🐦 Twitter: https://twitter.com/neuralnine
🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/
📁 GitHub: https://github.com/NeuralNine
🎙 Discord: https://discord.gg/JU4xr8U3dm
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from NeuralNine · NeuralNine · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
Python Beginner Tutorial #5 - Loops
NeuralNine
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
Python Beginner Tutorial #7 - Functions
NeuralNine
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
Python Beginner Tutorial #9 - File Operations
NeuralNine
Python Beginner Tutorial #10 - String Functions
NeuralNine
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
Python Intermediate Tutorial #6 - Queues
NeuralNine
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
Python Intermediate Tutorial #9 - Recursion
NeuralNine
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
Python Intermediate Tutorial #11 - Logging
NeuralNine
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
Python Machine Learning #4 - Support Vector Machines
NeuralNine
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
Making Text Images Readable Again with Python and OpenCV
NeuralNine
Neural Networks Simply Explained (Theory)
NeuralNine
Motion Filtering with OpenCV in Python
NeuralNine
Top 5 Programming Languages To Learn in 2020
NeuralNine
Simple TCP Chat Room in Python
NeuralNine
Image Classification with Neural Networks in Python
NeuralNine
Edge Detection with OpenCV in Python
NeuralNine
S&P 500 Web Scraping with Python
NeuralNine
Simple Sentiment Text Analysis in Python
NeuralNine
Introduction - Algorithms & Data Structures #1
NeuralNine
More on: Python for Data
View skill →Related Reads
📰
📰
📰
📰
Can AI Badger Reduce Local Coding Agent Token Usage?
Dev.to AI
Devin, the "First AI Software Engineer," Failed 86% of Its Benchmark Tasks, and Then What
Dev.to · Alex @ Vibe Agent Making
How I Built Captrix AI with Codex and TestSprite
Dev.to · ayush002jha
The Collapse of ‘Who Understands, Who Maintains’ — A Software Landscape in the AI Age
Medium · Programming
🎓
Tutor Explanation
DeepCamp AI