In-Class Coding Lab: Dictionaries

The goals of this lab are to help you understand:

  • How to use Python Dictionaries
  • Basic Dictionary methods
  • Dealing with Key errors
  • How to use lists of Dictionaries
  • How to encode / decode python dictionaries to json.

Dictionaries are Key-Value Pairs.

The key is unique for each Python dictionary object and is always of type str. The value stored under the key can be any Python type.

This example creates a stock variable with two keys symbol and name. We access the dictionary key with ['keyname'].


In [ ]:
stock = {} # empty dictionary
stock['symbol'] = 'AAPL'
stock['name'] = 'Apple Computer'
print(stock)
print(stock['symbol'])
print(stock['name'])

While Python lists are best suited for storing multiple values of the same type ( like grades ), Python dictionaries are best suited for storing hybrid values, or values with multiple attributes.

In the example above we created an empty dictionary {} then assigned keys symbol and name as part of individual assignment statements.

We can also build the dictionary in a single statement, like this:


In [ ]:
stock = { 'name' : 'Apple Computer', 'symbol' : 'AAPL', 'value' : 125.6 }
print(stock)
print("%s (%s) has a value of $%.2f" %(stock['name'], stock['symbol'], stock['value']))

Dictionaries are mutable

This means we can change their value. We can add and remove keys and update the value of keys. This makes dictionaries quite useful for storing data.


In [ ]:
# let's add 2 new keys
print("Before changes", stock)
stock['low'] = 119.85
stock['high'] = 127.0

# and update the value key
stock['value'] = 126.25
print("After change", stock)

Now you Try It!

Create a python dictionary called car with the following keys make, model and price. Set appropriate values and print out the dictionary.


In [ ]:
# TODO: Write code here

What Happens when the key is not there?

Let's go back to our stock example. What happens when we try to read a key not present in the dictionary?

The answer is that Python will report a KeyError


In [ ]:
print( stock['change'] )

No worries. We know how to handle run-time errors in Python... use try except !!!


In [ ]:
try:
    print( stock['change'] )
except KeyError:
    print("The key 'change' does not exist!")

Avoiding KeyError

You can avoid KeyError using the get() dictionary method. This method will return a default value when the key does not exist.

The first argument to get() is the key to get, the second argument is the value to return when the key does not exist.


In [ ]:
print(stock.get('name','no key'))
print(stock.get('change', 'no key'))

Now You try It!

Write a program to ask the user to input a key for the stock variable.

If the key exists, print the value, otherwise print 'Key does not exist'


In [ ]:
# TODO: write code here

Enumerating keys and values

You can enumerate keys and values easily, using the keys() and values() methods:


In [ ]:
print("KEYS")
for k in stock.keys():
    print(k)
    
print("VALUES")
for v in stock.values():
    print(v)

List of Dictionary

The List of Dictionary object in Python allows us to create useful in-memory data structures. It's one of the features of Python that sets it apart from other programming languages.

Let's use it to build a portfolio (list of 4 stocks).


In [ ]:
portfolio = [
    { 'symbol' : 'AAPL', 'name' : 'Apple Computer Corp.', 'value': 136.66 },
    { 'symbol' : 'AMZN', 'name' : 'Amazon.com, Inc.', 'value': 845.24 },
    { 'symbol' : 'MSFT', 'name' : 'Microsoft Corporation', 'value': 64.62 },
    { 'symbol' : 'TSLA', 'name' : 'Tesla, Inc.', 'value': 257.00 }    
]

print("first stock", portfolio[0])           
print("name of first stock", portfolio[0]['name'])   
print("last stock", portfolio[-1])          
print("value of 2nd stock",  portfolio[1]['value'])

In [ ]:
print("Here's a loop:")
for stock in portfolio:
    print(f"  {stock['name']} ${stock['value']}")

Now You Try it!

Write a for loop to print the stock symbol and value of all stocks.


In [ ]:
## TODO: Write code here

Putting It All Together

Write a program to build out your personal stock portfolio.

1. Start with an empty list, called portfolio
2. loop
3.     create a new stock dictionary
3.     input a stock symbol, or type 'QUIT' to print portfolio
4.     if symbol equals 'QUIT' exit loop
5.     add symbol value to stock dictionary under 'symbol' key
6.     input stock value as float
7.     add stock value to stock dictionary under 'value key
8.     append stock variable to portfolio list variable
9. time to print the portfolio: for each stock in the portfolio
10.    print stock symbol and stock value, like this "AAPL $136.66"

Metacognition

Please answer the following questions. This should be a personal narrative, in your own voice. Answer the questions by double clicking on the question and placing your answer next to the Answer: prompt.

Questions

  1. Record any questions you have about this lab that you would like to ask in recitation. It is expected you will have questions if you did not complete the code sections correctly. Learning how to articulate what you do not understand is an important skill of critical thinking.

Answer:

  1. What was the most difficult aspect of completing this lab? Least difficult?

Answer:

  1. What aspects of this lab do you find most valuable? Least valuable?

Answer:

  1. Rate your comfort level with this week's material so far.

1 ==> I can do this on my own and explain how to do it.
2 ==> I can do this on my own without any help.
3 ==> I can do this with help or guidance from others. If you choose this level please list those who helped you.
4 ==> I don't understand this at all yet and need extra help. If you choose this please try to articulate that which you do not understand.

Answer:


In [ ]:
# SAVE YOUR WORK FIRST! CTRL+S
# RUN THIS CODE CELL TO TURN IN YOUR WORK!
from ist256.submission import Submission
Submission().submit()