knowledge-kitchen / course-notes

Dictionaries - Basics (in Python)

Sequences refresher

# this will just print out lowercase foo
x = "foo"
x.upper()
print(x)
# this will print out uppercase foo
x = "foo"
x = x.upper()
print(x)

Dictionary basics

cat = {
  'breed' : 'sphynx',
  'color' : 'grey',
  'age' : 14,
  'name' : 'susha'
}

Some notable similarities and differences between dictionaries and lists

Examples

Basic list usage

#this is how you use lists...
cat = [
    'sphynx',
    'grey',
    14,
    'susha'
]

#read out the properties of the list
typeOfCat = cat[0]
ageOfCat = cat[2]
print("The " + typeOfCat + " is " + str(ageOfCat) + " old.")

Basic dictionary usage

#this is how you use dictionaries
cat = {
    'type': 'sphynx',
    'color': 'gray',
    'age': 14,
    'name': 'susha'
}

typeOfCat = cat['type']
ageOfCat = cat['age']
print("The " + typeOfCat + " is " + str(ageOfCat) + " old.")

Cat adoption system

cat_data.py

#list of cats
#each cat is a dictionary
#so this is a list that contains lots of dictionaries

cats = []
cats.append({
    'id': 100,
    'type': 'sphynx',
    'color': 'gray',
    'age': 14,
    'name': 'susha',
})
cats.append({
    'id': 8,
    'type': 'calico',
    'color': 'orange and black',
    'age': 4,
    'name': 'norman'
})
cats.append({
    'id': 29,
    'type': 'mao',
    'color': 'speckled gray',
    'age': 7,
    'name': 'arya'
})
cats.append({
    'id': 984,
    'type': 'tiger',
    'color': 'orange',
    'age': 88,
    'name': 'tony'
})
cats.append({
    'id': 7,
    'type': 'himalayan',
    'color': 'white',
    'age': 10,
    'name': 'thiksey'
})
cats.append({
    'id': 914,
    'type': 'short-haired',
    'color': 'green',
    'age': 2,
    'name': 'munchkin'
})

cat_adoption_system.py:

#the imported file creates a list of cats
from cat_data import *

#set up a blank shopping cart that will hold the user's preferred cats to adopt
shoppingCart = []

print("Welcome to the cat adoption system. Here are our available cats:\n")

for cat in cats:
    print(cat['id'], cat['name'], cat['age'], cat['color'], cat['type'])

#keep asking the user to enter cat ids until they enter 'exit'
id = ""
while id != 'exit':

    #ask the user which cat they'd like
    id = input("\nPlease enter the id of the cat you would like to adopt (enter 'exit' to quit'): ")

    #loop through the cats and find the one with the id that the user entered
    for cat in cats:
        if str(cat['id']) == id:
            #append the selected cat to the shopping cart
            shoppingCart.append(cat)

print("Thank you for shopping at our site!")

#output all items in the shopping cart
print("You have selected the following cats to adopt:\n")

#loop through the shopping cart and output the contents
for cat in shoppingCart:
    print(cat['id'], cat['name'], cat['age'], cat['color'], cat['type'])

More miscellaneous examples

# This one will print out 6 first characters
myfavoriteFood = "potato skins"
mySmallerFood = myFavoriteFood[0:6]
x = [
    "potatoes": "young",
    "tomatoes":"plum",
    "arugula": "baby",
    "milk": "vitamin fortified"
    ]

# loop through the items in the list
#each item comes as a key->value pair... so store them in varibles named key and variable
for k,v in x.items():
    print(k)
#List Review
shoppingList =[
    "tomatoes",
    "potatoes",
    "leeks",
    "filtered water",
    "organic grade A Vitamin AD fortified Milk"
    ]
smallerList = shoppingList [0:4]
smallerList.sort() #alphabetizing
x = {
    "potatoes": "young",
    "tomatoes": "plum",
    "arugula": "baby",
    "milk": "vitamin AD organic"
    }

for thing in x:
    print(thing) # This will print out the KEYS only
x = {
    "potatoes": "young",
    "tomatoes": "plum",
    "arugula": "baby",
    "milk": "vitamin AD organic"
    }
print(x["tomatoes"]) #this is indexing based on the keys - so this will print out "plum"
print(x.keys()) #this prints out keys only
print(x.values())#gives you values only
print(x.items())#gives you both keys and values
x = {
    "potatoes": "young",
    "tomatoes": "plum",
    "arugula": "baby",
    "milk": "vitamin AD organic"
    }

#loop through all the keys only
for k in x.keys():
    print(k) #looping keys

#loop through all the values only
for v in x.values():
    print(v) #looping value

#loop through all the key/value pairs
for k,v in x.items():
    print(k,v) #looping through both
x = {
    "potatoes": "young",
    "tomatoes": "plum",
    "arugula": "baby",
    "milk": "vitamin AD organic"
    }

#dictionaries are mutable data types - so this updates that the arugula is old not baby
x["arugula"] = "withered"

#loop through all the key/value pairs
for k,v in x.items():
    print(k,v)
#values of any immutable data type can be a key
x = {
    "foo": "hello",
    True: "goodbye",
    1.00: True,
    "hi": 1.2,
    None: ['a','b','c'],
    5: {'foo':'bar'}
    }

print(x[None])
grades = {}
askForMore = True
while askForMore:
    name = input("Please enter a student name: ") #key
    grade = input("What's their grade? ") #value
    grades[name] = grade
    #grades[key] = value
    another = input("Do you want to add in another student? ")
    if another.lower() == 'n' or another.lower() == "no":
        askForMore = False
#allow the user to look up the grade that corresponds with a particular student
name = input("Whose grade would you like to look up? ")
print(name + "'s grade is ", grades[name])
#if you use the same name twice, it'll give you the latest input