Python 3 - Classes vs Dictionaries

Sdílet
Vložit
  • čas přidán 14. 04. 2020
  • A comparison of a basic class and a dictionary. We will mimic the functionality of a class with a dictionary, but you will see that the class offers a nicer syntax and has a few more features.
  • Věda a technologie

Komentáře • 40

  • @bp56789
    @bp56789 Před 3 lety +5

    Fantastic tutorial. I've just started programming in Python, and I loved dictionaries and hated classes lol. But now it sounds like classes are just dictionaries (and therefore just as fast) but with much better syntax under some circumstances, such as when the value in the dictionary is a tuple of variables. Thank you.

    • @LukeBeenJammin
      @LukeBeenJammin  Před 3 lety +2

      If you prefer the dot syntax of classes, check out the Bunch library. It allows you to access dict keys with the dot operator as though the were classes (like JavaScript if you're familiar).
      pypi.org/project/bunch/

  • @Lich230
    @Lich230 Před 2 lety +3

    I had just learned up on classes and was missing how they were significantly different from dicts, thanks for the video!

  • @ep352
    @ep352 Před 3 lety +6

    Great video!!! Thank you for making it so much clear now what the actual benefits of using Classes are. For a beginner, who's gone along just fine with dictionaries, it wasn't too obvious.
    P. S I tried to go through your playlists to see what other uploads you have on a topic of Python; It would be immensely helpful if you could create a dedicated playlist for Python too.
    Thank you

  • @Kevinschart
    @Kevinschart Před 3 lety +1

    Hey man...BEAUTIFUL video! I was thinking that I would need to do exactly what you did here to help me sort out the difference between classes and dictionaries. I'm trying to break my scripting habit, and utilize more functions and classes...Returning dictionaries was my first idea, now I see that Classes are nothing more than an elegant way to manage dictionaries, with some additional advanced capabilities.
    This is the gold standard on teaching this topic as far as I'm concerned.

  • @javedsultan4830
    @javedsultan4830 Před 6 měsíci +1

    Great tutorial, instantly subscribed

  • @Gruuvin1
    @Gruuvin1 Před 6 měsíci +1

    For holding data, you might prefer dataclasses. For simple and non-volatile storage and portability, you might prefer the dictionary so you can serialize it with JSON.

    • @LukeBeenJammin
      @LukeBeenJammin  Před 6 měsíci +1

      Yep, good tip. Also the munch library, which can be installed from pip, is good if you like the JavaScript style objects. It combines the functionality of dictionaries with an object wrapper. I imagine there's an efficiency hit, but it makes for nicer looking code over dictionaries.

  • @MusicEffekt
    @MusicEffekt Před 7 měsíci +2

    please make the font a bit bigger on the screen. Thanks

  • @immanuelsuleiman7550
    @immanuelsuleiman7550 Před 3 lety +1

    Very well done
    I come from a c-sharp background but I've been riding python for the last 6 months or so
    I've gotten lazy and I tend to use dictionaries for everything
    Because c sharp is a statically typed language you don't really have that option
    I'm watching this video has reminded me of why design patterns based on classes are more efficient in the long run
    Great video

  • @marcjosephcole1208
    @marcjosephcole1208 Před 3 lety +1

    nice video. please continue making this type of tutorial, I'm a python beginner and I really want to get deep into it. thanks, new subscriber here

  • @BogdanBogdanovichBogdanov

    This was very good tutorial, thank you!

  • @azrulfyz1162
    @azrulfyz1162 Před 2 lety +1

    Thanks for this explaination, there is a lot of these classes and dict method used in machine learning libraries. I'm trying to make and modify according to my needs, but its quite difficult then I thought, since I am coming from a mt4 😍

  • @moralfuxery
    @moralfuxery Před 6 měsíci +1

    Forgot to say thanks for the video man, amazing job explaining. You have a talent for teaching for sure. Classes clicked for me about 13 mins in 🫰

  • @mistercakes
    @mistercakes Před 3 lety +1

    I've run into some limitations when creating class attributes based on the key name. e.g. Key has a string like 'name@english' or 'name.english'. What is your approach in cases like this?

    • @LukeBeenJammin
      @LukeBeenJammin  Před 3 lety

      I believe you can use the built-in global functions `getattr()` and `setattr()`. Here is a brief summary of `getattr()`:
      www.geeksforgeeks.org/python-getattr-method/
      Example:
      ```
      class Foo:
      pass
      obj = Foo()
      setattr(obj, "@key", "Winning!")
      print(getattr(obj, "@key")) # Winning!
      ```

  • @heatherbaroody8478
    @heatherbaroody8478 Před 3 lety +1

    Great video. Is there a substantial difference in memory/efficiency between storing variables in dictionaries vs classes

    • @LukeBeenJammin
      @LukeBeenJammin  Před 3 lety +1

      I don't know for certain, but I would think not. This might be something good to try to test for yourself using some profiling tools. In either case you have an object referencing identifiers which are storing values, so I would imagine that both implementations are extremely fast. You may want to check out some of these python3 profiling tools mentioned in this article. medium.com/swlh/4-simple-libraries-to-quickly-benchmark-python-code-8d3dfd288d7a

  • @sugataster
    @sugataster Před 3 lety +1

    Liked it.. Thank you

  • @markasiala6355
    @markasiala6355 Před 2 lety +1

    I thought perhaps you were going to go the __repr__ route in the class but you have to stop somewhere. Those helper functions really make integration of classes with standard functions behave nicely.

  • @pangyongray4235
    @pangyongray4235 Před 2 lety +1

    what if i wanna put a dictionary into a class, does that make sense?

    • @LukeBeenJammin
      @LukeBeenJammin  Před 2 lety +2

      Within a class you definitely can and often do have attributes that hold other objects and/or dictionaries.
      For me the general rule for a class is, if I am going to need a lot of these objects, and they all have a similar structure, then I will want to make a class. The general rule for a dictionary is when you don't know exactly how many items you are going to have. If I don't know how many items (attributes) I will have for the class, then that would be a bad choice, because we define those attributes up front.
      It's generally best to think of dictionaries as homogeneous collections of similar items that each have a string-based name. The same goes for lists. Most of the time a list is a collection of similarly structured items, each having a list index instead of a string-based name.
      A common strategy would be to use both a dictionary and a class, such that all of the keys in the dictionary hold an instance of a class. So I could have a `Person` class, and have a dictionary called `people`, where each key of the dictionary may be the person's ID, and the value would be the instance of the person class.

    • @douglasmckinley-sr1507
      @douglasmckinley-sr1507 Před rokem

      So the idea of using a dictionary with unique “key” and an the associated object as the “value” would be to speed up searches? It just occurred to me that might be the solution to a problem I have. I have many objects (100,000 objects) which are store locations that have an owner as one of the attributes. I would like to know how many stores the owner owns other than this store. For speed of processing on the client side I only need the count. I could make a dictionary with owner as the “key” and then a “list” of objects associated with that owner/key. When I create the object instance I could then add that object/location to the Owner’s dictionary’s object list. After creating the 100,000 objects I could update them with the number of locations that owner has. Thanks for the idea!

  • @moralfuxery
    @moralfuxery Před 6 měsíci +1

    So look, im at the of a programming class, and we ended eith python and only spent 2 weeks on it which i hate. Dictionaries throw me off right now, but classes clicked IMMEDIATELY with me. Someone thats baddass with this language, is it bad to just move forward using classes? They seem to serve the same purpose just a different way of getting there. Is all the same functionality there still? Has in if i wanted to retrieve data set in the class earlier to be called on way down the line for another function. Also cant figure out how to make a class, but have the input() place that data into it. 🧐
    Again, note, that i just started with Python but strong understanding of this area of study. We literally study everything but how to code (other than shell scripts, do ALOOOOOT of those) (im a CS/InfoSec student)

    • @LukeBeenJammin
      @LukeBeenJammin  Před 6 měsíci +1

      This video was primarily about the idea of "encapsulation" which is generally associated with Object Oriented Programming (classes). There are other ways to use dictionaries though.
      IMO a dictionary is best used as a variable sized collection of items, sort of like a list, but instead of using an index number to identify the items in the collection, you use a string name.
      Imagine a list of "Car" objects. Each car has a VIN number that uniquely identifies that car. Now let's say I know a car's VIN number and want to access the associated car object. With a list, I would have to look through each car one at a time until I found the car matching that VIN number. That could take a very long time with millions of cars. With a dictionary, if the VIN number was used as the string key, would instantly retrieve that car object.

    • @LukeBeenJammin
      @LukeBeenJammin  Před 6 měsíci

      One of the most important things I could impart to you is that actual coding matters. Theory is great, fun, and interesting. But if you want to get paid, you must learn to code whether your instructors have you do it in class or not.
      Start very small. Code small boring programs to start, so there is only a small number of things that can go wrong. This phase is tedious, but important, and can be fast if you just do it. Make super simple programs, like take notes in another class using print() commands in Python. Silly stuff like that. If you use it, you will get good. If you don't, you won't.

    • @moralfuxery
      @moralfuxery Před 6 měsíci +1

      @@LukeBeenJammin thanks for the reply man I'll take any advice I can get bc it's just an ocean of information that seems literally endless. But that's pretty much what I'm doing. Building small calculators, simple stuff like that. So I think I'm on the right path 🧐

  • @UnpluggedPerformance
    @UnpluggedPerformance Před 3 lety +1

    hey super thanks man, can you share the code, I know its not a lot of code to write, but its a little bit easier for us to copy and play with it to better understand your story

    • @LukeBeenJammin
      @LukeBeenJammin  Před 3 lety

      Unfortunately I use this as a learning device for some students, so I don't share the code, mostly to encourage them to get used to typing things out playing spot the differences. I'm glad you liked the video! Thank you for the feedback. In the future I will try to consider a way that I can share the code and still maintain a challenge for students.

    • @UnpluggedPerformance
      @UnpluggedPerformance Před 3 lety

      @@LukeBeenJammin ok thanks no worries
      for sharing the video though, nice one!

  • @OzturkCan
    @OzturkCan Před 7 měsíci

    Why didn’t you use print_basket(di_a) instead of di_a[“print_basket”](di_a) ? Couldn’t you have got this result without creating a new key in dict? 29:09

    • @LukeBeenJammin
      @LukeBeenJammin  Před 7 měsíci +1

      Yes I could have. However, in order for me to do that, both that function and the dictionary both have to be defined in my program scope. So if I were to pass my dictionary to another function in another module, I wouldn't have access to the function without also passing in the function. So it's easier to add the functionality to the dictionary itself. This is the concept of object oriented programming known as encapsulation. Encapsulation means to group all data and also the functions that operate on that data into one object. Then the data and the functionality can be passed around together in one parameter.

  • @nikhilpatil-of9vb
    @nikhilpatil-of9vb Před 2 lety

    Please make Playlist for python

  • @thairston1
    @thairston1 Před 3 lety

    # This is the dictionry
    pips = {"Tie":1, "Noah":2, "Ma":3, "rye":4, "Law":5, "shoe":6, "Cow":7, "ivy":8, "Bee":9, "Toe":10}
    # Request the user pick a number to the associated Key
    Peg = input(“ pick a number from 1-10 ” + pips [ ])
    Print(“This is your associated key ” + peg)
    #How do you get the associated user input to the dictionry?

    • @LukeBeenJammin
      @LukeBeenJammin  Před 3 lety

      In your code, `Peg` is an identifier (a variable) that holds some value. The value it holds, in this case, is the result of that `input()` function call. So a dictionary can store that same value with a string key `"Peg"`. So you can do this:
      ```
      pips["Peg"] = input("Pick a number: ")
      ```

  • @leecaste
    @leecaste Před 3 lety

    This is a weird example, you are creating a dictionary for each key-value pair but usually dictionaries are used to hold more than one of these, you should have apples, bananas and cranberries all in one dictionary with their correspondong values.
    How would you do that in a class?
    How would you add key-value pairs to the class without knowing, how many they are in advance like using a for loop with hundreds of key-value pairs?

    • @LukeBeenJammin
      @LukeBeenJammin  Před 3 lety

      Generally speaking, if you don't know how many things you will have in the collection, you'd want to use a dictionary. Classes are usually used for more well defined objects where the set of attributes don't change. However that's not a hard and fast rule, as Python allows you to dynamically add properties to objects. For example, there is a Python package you can install with pip called "bunch" which allows you to create Bunch() objects that act more like a JavaScript object, in that it acts as a dictionary and also as an object created by a class.
      In any object if you want to iterate over it's attributes you can use the dir() function to get a list of the attribute names. You can then combine that with the gettattr() to see what the attribute values are.

    • @leecaste
      @leecaste Před 3 lety

      I see, thank you 👍

  • @ander172
    @ander172 Před 6 měsíci

    Your keyboard is so loud. 😪😪

  • @antiquarian1773
    @antiquarian1773 Před 3 lety

    print("good video dude".title())