Dictionaries - CS50P Shorts

CS50 · Beginner ·💻 AI-Assisted Coding ·2y ago

Key Takeaways

Explains dictionaries in Python, using a program that creates a report on a spacecraft as an example, demonstrating how to store and access key-value pairs

Full Transcript

[Music] well hello and and all and Welcome to our short on dictionaries now dictionaries are useful when you want to store similar kinds of information in terms of these key value pairs so more on that in a moment but let's first dive into our scenario here I have here a program called report. where the goal is to write a report on some given spacecraft that's out there in the universe and notice how here I have a function called create report that takes as input something called spacecraft an argument here called spacecraft and my goal is to well one hopefully make sure this report actually has the information I'm looking for and then return that report for printing perhaps up in main over here now we said that dictionaries are good for storing collections of related information and I think a spacecraft kind of qualifies in this sense spacecraft has something like a name maybe like a distance from Earth let's say something a spacecraft could be good to represent with a dictionary well let's try this out here I'll go ahead up to main here and I will create our very first spacecraft that I'll call in this case just spacecraft and I'll set spacecraft equal to well a dictionary and so we've seen that a dictionary begins with these curly braces whereas a list begins with square brackets a dictionary is noted with these curly braces here now a dictionary of course comes with these keys and values now a key is simply some name so we accessing some particular value inside of this dictionary and maybe the first key we should have here is some attribute of our spacecraft maybe its name for instance so I'll say here one of our keys is name and syntax wise what I have to do when I specify a key is this I give the name of the key in this case the name of the key literally is name I can then type colon followed by the value I hope for this key to represent so in this case maybe let's talk about uh let's talk about Voyager one which is the furthest man-made spacecraft really any kind of object away from Earth Voyager one here so here our spacecraft is a dictionary and we have one key name that is assigned the value Voyager one but of course there are more uh really properties of Voyager one we can actually put inside of this dictionary one of them is distance distance and we said Voyager one is the furthest manade object from from Earth so we'll go ahead and say that this is 163 astronomical units away which is on the order of I would say billions of miles away go ahead and look up what that conversion is on your own so here we have Voyager 1 and we also have a distance of 163 Au and this together forms our spacecraft so if I want to create a report on this spacecraft I could as we said before maybe print the result of create report but then give as input our spacecraft down below and hopefully if we run python report. H well we see a report like I argue that create report is returning us some text and we're printing it in main but we haven't fixed these to-dos so we have here our own dictionary with keys and values that we have specified but if you want to access those values given some key well we can do that perhaps in create report now in general we could assume let say that crate report is given some spacecraft that is a dictionary with these two keys name and distance and the goal here is really to just access the values at those keys so I could use here our python FST string and use curly braces of my own these are not curly braces for a dictionary these are curly braces for interpolating some value I can put in Python code here to get some value and actually incorporate it into this text called report here so for the name of our spacecraft we know we have a dictionary that's called spacecraft being passed as input to create report and we also know we can assume in this case that this dictionary will have a key called name all lowercase so to access the value at this key we can use brackets followed by the actual key uh of our actual name of our key in this case the name of our key key literally is name so here to be clear what we'll do is go ahead and interpolate some value inside of this F string and this value will be the value we access by accessing the name the key name as part of our spacecraft dictionary here let's do the same thing now for distance we can assume that our spacecraft dictionary also has a key called distance just like this and now if we were to rerun this report I think we'd see that we got report back with our name being Voyager 1 and our distance being 163 but there are no units here so let's go ahead and actually add this in 163 auu or astronomical units all right so this is our report and you kind of get a sense for how handy these things like dictionaries can be we are able here to combine various pieces of information the name of our spacecraft the distance and then access it very easily using these keys that we have down below now what might go wrong with dictionaries well let's say we're not using uh Voyager one anymore we're using a new spacecraft or more specifically a kind of telescope called the James web Space Telescope one of the most recent space telescopes created that can help us see far beyond in the reaches of space so here I'll make a new dictionary and I'll set the name to James web Space Telescope but I'm actually not quite sure how far away this telescope scope is from Earth so I'll leave that key empty here well I can go ahead and try to run python of report. but before I do maybe think about what might go wrong when I call create report let's see here I'll hit enter and I'll actually get what's called a key error down below I see key error colon distance and it seems to me that we tried to access this key named distance in great report but our assumption was not quite correct spacecraft does not have a key called distance so let's go ahead and add that key here well it turns out that to add a new key to a dictionary I don't need to just simply create it as a dictionary is being built I could also do this I could go ahead and try to try to do spacecraft bracket distance much like the syntax down below to access this key but then Supply some value in this case I could say that it is I think let me just check here it is 01 Au away from Earth so actually interestingly the James web Space Telescope kind of orbits the Sun in a kind of constant distance around from Earth so about 01 Au here let's go ahead and run this report again I'll say python of report. Pi and now we'll see that our report has been fixed for us down below Okay so we've seen here various ways to add add keys to dictionaries various ways to access those keys and to create our own dictionary let's consider more ways to actually access these values for a given key let's go back a little bit and this when we actually don't have this value 0.01 we have just here the key name what could we do perhaps maybe uh May uh anticipate this error and make create report a little more flexible with the kinds of input it might get well it turns out that to access some key we don't need to always use this bracket notation in fact there is some other method one called get we can use to try to access some key and if that key doesn't exist we'll actually get some other value we specify instead so here perhaps in uh distance I could instead of using bracket distance here I could use. getet so the name of my dictionary spacecraft doget followed by the key I hope to access in my dictionary in this case distance I could if I wanted to supply another value that will actually be returned if this distance key is not part of my dictionary and we saw earlier that distance is not part of this dictionary so what we should hopefully see instead is unknown well want going to go ahead and try python of report. piy hit enter and now we'll actually see that get returned to us unknown instead of of the actual value for this non-existent key this avoids the key error we saw earlier as well so let's try this here I'll do spacecraft. getet and I'll try to get the name of the spacecraft otherwise we can go ahead and return unknown as well so in general you'll find that most of the time you can use that same bracket notation we saw earlier but if you are aren't sure if some key will exist you could use get to try to get that key but return some other value if that key in fact does not exist inside of the J inside of your particular dictionary in this case so I believe this gives us an example of how we can go ahead and get our keys let's now explore other ways to add Keys Beyond just the same syntax we saw earlier as well so recall we could go ahead and add in a key by creating our dictionary up here I could say distance uh distance colon Etc here I could even do some syntax like this spacecraft distance uh equals let's say 0.01 these are two ways to add keys to a dictionary turns out there's also one more to be familiar with as well if I wanted to add not just one key at a time to my dictionary but maybe multiple at once I could use a method called update so I could type the my dictionary followed by a DOT and then update up dat just like this an update takes as an argument as an input here another dictionary but it will really take that dictionary's keys and values and just add them to the dictionary I started with here in this case spacecraft so we'll update spacecraft with all of the keys and values that I provide as input to update now I could go ahead and specify here in in another dictionary uh maybe the distance which we said before was 0.01a U and then we can maybe specify another attribute maybe the orbit here as you said before the James web Space telecope Telescope orbits the Sun in this case so here I'm trying to add now two new keys one called distance and one called orbit each with their own values I could also go down below here and I could add in some new line of my report maybe I'll say orbit and that is equal to maybe spacecraft. getet uh the key called orbit otherwise we'll return unknown if that key perhaps doesn't exist down below all right so here we've tried to add here two new keys at once to our dictionary up above let's go ahead and run Python report. piy and now we'll see that those keys are in fact part of our dictionary thanks to update as well so now we've seen how to add keys in various ways how to act access keys in various ways but let's see some other utility features of dictionaries as well I'll actually go ahead and remove what I have here and why don't we try to make a new program uh one called distances. Pi now in distances. pi we're going to treat dictionaries a little bit differently I'm going to make a dictionary where I have the names of my spacecraft in one column if you will and the distances of those spacecraft in another column if you will my dictionary so for instance I can make a dictionary called distances and open up some curly braces here and as the keys in this dictionary I'll go ahead and have the names of spacecraft like Voyager 1 for instance now the value of this particular key will be the distance that Voyager one is away from Earth which happens to be 163 Au as we saw before now I can go ahead and add other keys to my dictionary other spacecraft and their distances I can also go ahead and add Voyager 2 which happens to be 136 Au away from Earth I could go ahead and add Pioneer Pioneer 10 which is about 80 Au away uh New Horizon another probe which is about 58 Au away and finally Pioneer 11 which is about 44 Au away so notice how here my dictionary is representing multiple spacecraft but I'm really defining the relationship between my spacecraft names and their distances as well so with my information presented like this I could try to maybe print out each of their names and their distances using some key functionalities of dictionaries here I'll go ahead and Define myself a function called Main and I'll leave that empty for now I'll go down below and make sure I call Main and now within main my goal is to for each uh spacecraft I have inside of the dictionary print out its name and the distance away from Earth so if I want to do something for each uh let's say anything I have a good idea is to use a for Loop in this case I want to do something for each key I have in my dictionary what turns out the dictionaries come with a method called keys that returns to me all the keys in my dictionary so I could type for name in distances. Keys and again do keys this method here that will return to me all of the keys in my dictionary so first Voyager one then Voyager 2 then Pioneer 10 New Horizons Pioneer 11 these will all be part of the return value of do Keys when called on the distances dictionary and now I'm saying for name in that list of keys so first name will be equal to Voyager 1 then Voyager 2 then Pioneer 10 as my for Loop continues in the code indented here on line 12 so now that I have name which will first be Voyager 1 Voyager 2 I might also want to access in this case the distances of those probes from Earth and to do that I could actually maybe plug in my key to my dictionary and get back the value I'm looking for let's demonstrate this here I'll type print and I'll use an F string and I'll then say name referring to the name of my spacecraft is and then some distance away from Earth but again we have here name which is in fact a key of our dictionary so I could type distances bracket name to access the value for each of these various keys I'm getting for instance when name is equal to Voyager 1 I'll get back 163 right here when name is equal to Voyager 2 well I'll get back 136 right down here so I could complete the sentence by saying name is some distance in AU from Earth just like that let's go ahead and try running this I'll say python of distances. Pi and we'll see here some other reports on our spacecraft Voyager 1 is 163 AU from Earth Voyager 2 is 136 AU from Earth so when you want to do some kind of code like this online 12 for for each key in your dictionary you could use dot keys to access each of those keys and loop over them perhaps with something like a for Loop one more to be familiar with here we can also Loop over let's say the values in our dictionaries so just like we have keys we also have values as well values and let's try maybe converting these Au to meters instead a much more friendly unit of measurement so I'll go ahead and replace this code down below here and why don't I actually delete this for Loop here and first give myself a function to convert Au to convert Au into in this case meters it turns out that uh the number of meters corresponding to 1 Au is this big number here I'm not even sure how to pronounce it but I will make sure type incorrectly 5 97 87 07 0 0 and I believe this is correct 870 597 149 yes this really big number that I don't know how to pronounce is the number of meters in one given Au U so if we wanted to perhaps Loop over all of our values in the dictionary so first 163 then 136 then 80 and so on we could use a four loop I could say four perhaps distance in distances. value values and then I could perhaps print using an F string the distance in AU is the converted distance in meters so to be clear here a function called convert that takes some amount of au and converts it to meters then in main we go through each value in our dictionaries values and then we'll go ahead and convert that distance to meters and also print out the distance in AU so I'll go ahead here and I'll run python of distances. Pi and now we'll hopefully see down below all of these distances in AU now in meters so we've seen a lot about dictionaries we've seen back in report. piy how to create them how to supply keys and values we've seen how to update our dictionaries whether using the update method or by using bracket notation we saw a little earlier too we've seen how to access those values given some key we've seen the get method down below as well as the more simple bracket notation too and over in distances. pi we've seen how to Loop over the keys and the values in our dictionaries that's it here for our short on dictionaries we'll see you next time

Original Description

*** This is CS50, Harvard University's introduction to the intellectual enterprises of computer science and the art of programming. *** HOW TO SUBSCRIBE http://www.youtube.com/subscription_center?add_user=cs50tv HOW TO TAKE CS50 edX: https://cs50.edx.org/ Harvard Extension School: https://cs50.harvard.edu/extension Harvard Summer School: https://cs50.harvard.edu/summer OpenCourseWare: https://cs50.harvard.edu/x HOW TO JOIN CS50 COMMUNITIES Discord: https://discord.gg/cs50 Ed: https://cs50.edx.org/ed Facebook Group: https://www.facebook.com/groups/cs50/ Faceboook Page: https://www.facebook.com/cs50/ GitHub: https://github.com/cs50 Gitter: https://gitter.im/cs50/x Instagram: https://instagram.com/cs50 LinkedIn Group: https://www.linkedin.com/groups/7437240/ LinkedIn Page: https://www.linkedin.com/school/cs50/ Medium: https://cs50.medium.com/ Quora: https://www.quora.com/topic/CS50 Reddit: https://www.reddit.com/r/cs50/ Slack: https://cs50.edx.org/slack Snapchat: https://www.snapchat.com/add/cs50 SoundCloud: https://soundcloud.com/cs50 Stack Exchange: https://cs50.stackexchange.com/ Telegram: https://t.me/cs50x Threads: https://www.threads.net/@cs50 TikTok: https://www.tiktok.com/@cs50 Twitter: https://twitter.com/cs50 Twitter Community: https://twitter.com/i/communities/1722308663522594923 YouTube: http://www.youtube.com/cs50 HOW TO FOLLOW DAVID J. MALAN Facebook: https://www.facebook.com/dmalan GitHub: https://github.com/dmalan Instagram: https://www.instagram.com/davidjmalan/ LinkedIn: https://www.linkedin.com/in/malan/ Quora: https://www.quora.com/profile/David-J-Malan Threads: https://www.threads.net/@davidjmalan TikTok: https://www.tiktok.com/@davidjmalan Twitter: https://twitter.com/davidjmalan *** CS50 SHOP https://cs50.harvardshop.com/ *** LICENSE CC BY-NC-SA 4.0 Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License https://creativecommons.org/licenses/by-nc-sa/4.0/ David J. Malan https://cs.harvard.edu/malan m
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from CS50 · CS50 · 0 of 60

← Previous Next →
1 Hello, World: Hadi Partovi
Hello, World: Hadi Partovi
CS50
2 Content Distribution and Archival in a Digital Age
Content Distribution and Archival in a Digital Age
CS50
3 CS50 2014 - Week 1
CS50 2014 - Week 1
CS50
4 CS50 2014 - Week 3
CS50 2014 - Week 3
CS50
5 CS50 2014 - Week 0, continued
CS50 2014 - Week 0, continued
CS50
6 CS50 2014 - Week 4
CS50 2014 - Week 4
CS50
7 Week 3, continued
Week 3, continued
CS50
8 Quiz 0 Review
Quiz 0 Review
CS50
9 CS50 2014 - Week 3, continued
CS50 2014 - Week 3, continued
CS50
10 CS50 2014 - Week 7
CS50 2014 - Week 7
CS50
11 CS50 2014 - Week 7, continued
CS50 2014 - Week 7, continued
CS50
12 Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
CS50
13 Introduction to Amazon Web Services by Leo Zhadanovsky
Introduction to Amazon Web Services by Leo Zhadanovsky
CS50
14 CS50 2014 - Week 9
CS50 2014 - Week 9
CS50
15 How to Build Innovative Technologies by Abby Fichtner
How to Build Innovative Technologies by Abby Fichtner
CS50
16 Light Your World (with Hue Bulbs) by Dan Bradley
Light Your World (with Hue Bulbs) by Dan Bradley
CS50
17 Building Dynamic Web Apps with Laravel by Eric Ouyang
Building Dynamic Web Apps with Laravel by Eric Ouyang
CS50
18 CS50 2014 - CS50 Lecture by Steve Ballmer
CS50 2014 - CS50 Lecture by Steve Ballmer
CS50
19 CS50 2014 - Week 10
CS50 2014 - Week 10
CS50
20 This is CS50 with Steve Ballmer?
This is CS50 with Steve Ballmer?
CS50
21 Meteor: a better way to build apps by Roger Zurawicki
Meteor: a better way to build apps by Roger Zurawicki
CS50
22 Data Analysis in R by Dustin Tran
Data Analysis in R by Dustin Tran
CS50
23 Data Visualization and D3 by David Chouinard
Data Visualization and D3 by David Chouinard
CS50
24 CS50 2014 - Week 6
CS50 2014 - Week 6
CS50
25 Build Tomorrow's Library by Jeffrey Licht
Build Tomorrow's Library by Jeffrey Licht
CS50
26 CS50 2014 - Week 9, continued
CS50 2014 - Week 9, continued
CS50
27 Essential Scale-Out Computing by James Cuff
Essential Scale-Out Computing by James Cuff
CS50
28 iOS App Development with Swift by Dan Armendariz
iOS App Development with Swift by Dan Armendariz
CS50
29 Sam Clark Leads Yale Students on Tour to CS50 at Harvard
Sam Clark Leads Yale Students on Tour to CS50 at Harvard
CS50
30 3D Modeling and Manufacture by Ansel Duff
3D Modeling and Manufacture by Ansel Duff
CS50
31 CS50 2014 - Week 5, continued
CS50 2014 - Week 5, continued
CS50
32 hello, world
hello, world
CS50
33 CS50 2014 - Deep Thoughts - Hash Table
CS50 2014 - Deep Thoughts - Hash Table
CS50
34 CS50 2014 - Deep Thoughts - Binary Tree
CS50 2014 - Deep Thoughts - Binary Tree
CS50
35 CS50 2014 - Deep Thoughts - Scratch
CS50 2014 - Deep Thoughts - Scratch
CS50
36 CS50 2014 - Deep Thoughts - MySQL
CS50 2014 - Deep Thoughts - MySQL
CS50
37 LaunchCode Visits CS50
LaunchCode Visits CS50
CS50
38 CS50 Live, Episode 100
CS50 Live, Episode 100
CS50
39 CS50 Field Trip to Google
CS50 Field Trip to Google
CS50
40 This is CS50 AP
This is CS50 AP
CS50
41 Week 4: Monday - CS50 2011 - Harvard University
Week 4: Monday - CS50 2011 - Harvard University
CS50
42 Week 2: Wednesday - CS50 2011 - Harvard University
Week 2: Wednesday - CS50 2011 - Harvard University
CS50
43 Week 1: Wednesday - CS50 2011 - Harvard University
Week 1: Wednesday - CS50 2011 - Harvard University
CS50
44 Week 11: Monday - CS50 2011 - Harvard University
Week 11: Monday - CS50 2011 - Harvard University
CS50
45 Week 3: Wednesday - CS50 2011 - Harvard University
Week 3: Wednesday - CS50 2011 - Harvard University
CS50
46 Week 12: Monday - CS50 2011 - Harvard University
Week 12: Monday - CS50 2011 - Harvard University
CS50
47 Week 1: Friday - CS50 2011 - Harvard University
Week 1: Friday - CS50 2011 - Harvard University
CS50
48 Week 3: Monday - CS50 2011 - Harvard University
Week 3: Monday - CS50 2011 - Harvard University
CS50
49 Week 10: Wednesday - CS50 2011 - Harvard University
Week 10: Wednesday - CS50 2011 - Harvard University
CS50
50 Week 2: Monday - CS50 2011 - Harvard University
Week 2: Monday - CS50 2011 - Harvard University
CS50
51 Week 9: Monday - CS50 2011 - Harvard University
Week 9: Monday - CS50 2011 - Harvard University
CS50
52 Week 7: Monday - CS50 2011 - Harvard University
Week 7: Monday - CS50 2011 - Harvard University
CS50
53 Week 5: Monday - CS50 2011 - Harvard University
Week 5: Monday - CS50 2011 - Harvard University
CS50
54 Week 5: Wednesday - CS50 2011 - Harvard University
Week 5: Wednesday - CS50 2011 - Harvard University
CS50
55 Week 7: Wednesday - CS50 2011 - Harvard University
Week 7: Wednesday - CS50 2011 - Harvard University
CS50
56 Week 8: Monday - CS50 2011 - Harvard University
Week 8: Monday - CS50 2011 - Harvard University
CS50
57 Week 9: Wednesday - CS50 2011 - Harvard University
Week 9: Wednesday - CS50 2011 - Harvard University
CS50
58 Week 8: Wednesday - CS50 2011 - Harvard University
Week 8: Wednesday - CS50 2011 - Harvard University
CS50
59 Week 10: Monday - CS50 2011 - Harvard University
Week 10: Monday - CS50 2011 - Harvard University
CS50
60 Week 2: Wednesday - CS50 2010 - Harvard University
Week 2: Wednesday - CS50 2010 - Harvard University
CS50

Related Reads

📰
Grok Walks Off With Your Repo? When the "Smartest Assistant" Becomes the Most Dangerous Tool
Learn how to protect your code repository from AI coding tools like Grok Build that can potentially compromise your project's security and integrity
Dev.to · Dufrence
📰
VSCode + ZooCode + Chinese AI Models: Complete Setup Guide
Integrate Chinese AI models into VSCode using ZooCode for enhanced coding assistance
Dev.to AI
📰
I Don’t Write Code the Way I Used To — And Neither Will You
Learn how AI-powered tools are changing the way developers work and why you should adapt to these changes
Medium · Programming
📰
How I Built an AI Interview Preparation Platform
Learn how to build an AI interview preparation platform to help candidates practice and improve their interview skills
Dev.to · zaki kasmi
Up next
Claude Code SEO: The Full AEO/GEO Method in 15 Minutes (STEAL THIS)
Income stream surfers
Watch →