Python Dictionaries
Creating and Accessing:
- A dictionary is like a Map in other programming languages, you specify keys and their values, then you can access each value with its key
- You can use other data types, not only strings. For example the key could be an integer and the value could be a float
- The same dictionary doesn't have to have all keys of the same type, or all values of the same type.
Add a new key-value pair :
- If the specified key doesn't already exist, it will add it. Otherwise it will replace its value with this one
Delete a key-value pair :
Delete all key-value pairs :
Check for key :
Loop though keys :
Loop though values :
- You can also get both keys and values as a tuple by using the .items() function
Combine Dictionaries
- If a key is already there, the value will be updated to the new value; otherwise the key-value pair will be added as a new entry
- If you have an existing dictionary, you can pass that as a parameter to the update function rather than defining a new one
Get a Copy
- This gets a new dictionary with the same key-value pairs, it will not be changed by changing the original
Challenge
Create a report card dictionary that has six entries, each with a course name as the key and a numeric score as the value. Combine it with a dictionary that has two different courses as well as one course that is the same but with a new grade. Then loop through all of the entries, displaying the course and grade for each.