Python for Absolute Beginners Transcripts
Chapter: Cleaner code with common data structures
Lecture: Concept: Dictionaries
0:00 Let's quickly review dictionaries, as that's going to be the focus of the rest of this chapter.
0:06 To create a dictionary, we can either use curly braces or we can use this dict(). Just like we can also use list, instead of square bracket.
0:15 Like we did in the demo, we can create a dictionary with the curly braces. We can create a dictionary by saying dict.
0:21 Now you might wonder if we can also create sets using curly braces, and we say curly brace. What do we get?
0:27 Well, it's decided that dictionaries are more common and without items in there, you can't distinguish are there pairs of items, or individual?
0:34 So this also means create dictionaries. We could also create them populated like this. Using keyword arguments, so dict Bill equals two
0:42 Zoey equals 7, Michael equals 4. That's the exactly the same in terms of the outcome as writing what we have right here, so same idea.
0:50 If we want to get one of the elements out, like if we want to know the value that Zoey has, then maybe we have
0:56 a variable, right now it has a value Zoey. So we could print wins by name, so Zoey R, whatever the value comes out.
1:04 So D bracket, that key, you're going to pull out that value. The key is Zoey. The value is 7. So it's going to print, wins by Zoey R 7.
1:11 Maybe some capitalization and punctuation as usual going on here, but, you know this is what the code does.
1:17 We also saw that if you say d bracket a key, and the key is not in the dictionary, it doesn't just not give you something back, it crashes.
1:24 So you might not want that. You might want to use this safer version of .get and then pass the name.
1:30 So dot get name, give us wins, if there's wins, we can print there are seven wins. Otherwise, we can say this player's never played a game with us.
1:38 Okay, so that's a useful way, if you're unsure if data is in the dictionary. These are super powerful.
1:43 It takes a little while to get your mind around them. But once you do, they're really, really great to work with.