Home API Notes

Lesson 2: Dictionary's and 2 Dimensional Arrays

Advay Shindikar and Amay Advani

Objective:

  • Understand the concept of dictionaries and how they can be applied
  • Learn how to add, modify, and delete entries in a dictionary using the assignment operator and the del keyword
  • Understand the concept of 2D arrays and how they can be used to store data in rows and columns
  • Learn how to create a 2D array in Python using a nested list
  • Understand how to access values in a 2D array using row and column indices
  • Learn how to use indexing and slicing to access a subset of a 2D array

student = {'name': 'Advay', 'age': 16, 'Sophomore'}
students = ['advay', 'amay', 'rohin', 'alex', 'ethan']

Check In:

  • Of the above code segments, which is a list and which is a dictionary?
  • What is a dictionary and how is it used?
  • What is a 2D Array?
  • How are 2D Arrays different from 1D Arrays or Lists and what can they be used for?

Manipulating Dictionaries

grocery_dict = {}

# ask the user to enter grocery items and their prices
while True:
    item = input("Enter an item for your grocery list (or 'done' to exit): ")
    if item == "done":
        break
    else:
        price = float(input("Enter the price of {}: ".format(item)))
        grocery_dict[item] = price

# print the grocery list and total cost
total_cost = 0
while True:
    print("Your grocery list:")
    for item, price in grocery_dict.items():
        print("- {}: ${}".format(item, price))
    print("Total cost: ${}".format(total_cost))
    
    # ask the user to choose an action
    action = input("What would you like to do? (add/remove/done) ")
    
    # add a new item to the grocery list
    if action == "add":
        item = input("Enter the name of the item you would like to add: ")
        price = float(input("Enter the price of {}: ".format(item)))
        grocery_dict[item] = price
        total_cost += price
    
    # remove an item from the           j
        item = input("Enter the name of the item you would like to remove: ")
        if item in grocery_dict:
            total_cost -= grocery_dict[item]
            del grocery_dict[item]
        else:
            print("Item not found in grocery list!")
    
    # exit the loop and print the final grocery list and total cost
    elif action == "done":
        break

print("Final grocery list:")
for item, price in grocery_dict.items():
    print("- {}: ${}".format(item, price))
print("Total cost: ${}".format(total_cost))