Dictionaries Python.

Slides:



Advertisements
Similar presentations
Procedures and Functions. What are they? They are both blocks of code that can be reused to perform specific task. However there is a difference: Function-
Advertisements

This Week More Types boolean string Modules print statement Writing programs if statement Type boolean.
Order of operators: x ** y x * y, x / y, x // y, x % y x + y, x - y
Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Functions. A set of statements (lines of code) that can be run repeatedly Goals: Learning Python by Lutz and Ascher –Code reuse –Procedural decomposition.
Structured programming
Introduction to Python
Main task -write me a program
* Just the gist? * Lots of details? * Specific steps? * What language ?
CS 116 Tutorial 5 Introduction to Python. Review Basic Python Python is a series of statements def f(p1, p2,…pn): x = 5 if x > p1: x = p1 + p2 return.
Python.
INLS 560 – V ARIABLES, E XPRESSIONS, AND S TATEMENTS Instructor: Jason Carter.
Python Programming Fundamentals
The University of Texas – Pan American
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Line Continuation, Output Formatting, and Decision Structures CS303E: Elements of Computers and Programming.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
CPTR 124 Review for Test 1. Development Tools Editor Similar to a word processor Allows programmer to compose/save/edit source code Compiler/interpreter.
Data Types Integer 15 StringHelloThere! Float/Real BooleanYes / No CharP.
Course A201: Introduction to Programming 11/04/2010.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Writing JavaScript Functions. Goals By the end of this unit, you should understand … How to breakdown applications into individual, re-usable modules.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Python Functions.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Lecture 5: Stopping with a Sentinel. Using a Sentinel Problem Develop a class-averaging program that will process an arbitrary number of grades each time.
Decision Structures, String Comparison, Nested Structures
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
INLS 560 – F UNCTIONS Instructor: Jason Carter.
Last Week Modules Save functions to a file, e.g., filename.py The file filename.py is a module We can use the functions in filename.py by importing it.
Python Let’s get started!.
1 CS 177 Week 6 Recitation Slides Review for Midterm Exam.
Introduction to Programming Python Lab 3: Arithmetic 22 January PythonLab3 lecture slides.ppt Ping Brennan
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
The fourth programming assignment J.-F. Pâris Fall 2015.
Lab 9 Exercises.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 3: Built-in functions.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
MapReduce, Dictionaries, List Comprehensions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
Find LCM Least Common Multiple of 3 and 5: List the Multiples of each number, The multiples of 3 are 3, 6, 9, 12, 15, 18,... etc The multiples of 5 are.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
Learning to use a ‘For Loop’ and a ‘Variable’. Learning Objective To use a ‘For’ loop to build shapes within your program Use a variable to detect input.
CS1022 Computer Programming & Principles
Python Let’s get started!.
Introduction to Python
Line Continuation, Output Formatting, and Decision Structures
When to use Tuples instead of Lists
Variables, Expressions, and IO
Functions CIS 40 – Introduction to Programming in Python
ALGORITHMS AND FLOWCHARTS
Line Continuation, Output Formatting, and Decision Structures
CSCE 206 Lab Structured Programming in C
ALGORITHMS AND FLOWCHARTS
I210 review.
Writing Functions( ) (Part 4)
Writing Functions( ) (Part 4)
Best Practices for Teaching Online
Adapted from slides by Marty Stepp and Stuart Reges
Python Basics with Jupyter Notebook
Hint idea 2 Split into shorter tasks like this.
CSCE 206 Lab Structured Programming in C
IST256 : Applications Programming for Information Systems
Python Reserved Words Poster
Programming Techniques
Presentation transcript:

Dictionaries Python

Dictionaries are defined with curly brackets

A dictionary is similar to a list, but you access values by looking up a key instead of an index. A key can be any string or number.

Inserting new values onto the end of your dictionary

Can you spot the errors in this code? Items can be removed using the del command, it will remove the key and the associated value.

# key - animal_name : value - location zoo_animals = { 'Unicorn' : 'Cotton Candy House', 'Sloth' : 'Rainforest Exhibit', 'Bengal Tiger' : 'Jungle House', 'Atlantic Puffin' : 'Arctic Exhibit', 'Rockhopper Penguin' : 'Arctic Exhibit'} # A dictionary (or list) declaration may break across multiple lines # Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.) del zoo_animals['Unicorn'] del zoo_animals['Sloth'] del zoo_animals['Bengal Tiger'] zoo_animals['Rockhopper Penguin'] = 'Penguin' print (zoo_animals) Solution

Distionaries can also contain lists that are accessed by a key

You can manipulate lists inside dictionaries exactly the same way as ordinary lists

Output You can use for loops to go through a dictionary, but be aware they are unordered they will come out in a random order

What is happening in this code?

Combining functions, for loops and dictionaries

Instructions Create three dictionaries: lloyd, alice, and tyler. Give each dictionary the keys "name","homework", "quizzes", and "tests". Have the "name" key be the name of the student (that is, lloyd's name should be "Lloyd") and the other keys should be an empty list. Task 1

lloyd = {"name":"Lloyd","homework":[],"quizzes":[],"tests":[]} alice = {"name":"Alice","homework":[],"quizzes":[],"tests":[]} tyler = {"name":"Tyler","homework":[],"quizzes":[],"tests":[]} Task 1 Solution

Instructions Now fill out your lloyd dictionary with the appropriate scores. To save you some time, we've filled out the rest for you. Homework: 90.0, 97.0, 75.0, 92.0 Quizzes: 88.0, 40.0, 94.0 Test Scores: 75.0, 90.0 Make sure to include the decimal points so your grades are stored as floats!  alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] Task 2

lloyd = { "name": "Lloyd", "homework": [90. 0, 97. 0, 75. 0, 92 lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] Task 2 solution

Instructions Below your code, create a list called students that contains lloyd, alice, and tyler. Task 3

lloyd = { "name": "Lloyd", "homework": [90. 0, 97. 0, 75. 0, 92 lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] students = [lloyd,alice,tyler] Task 3 Solution

Instructions for each student in your students list, print out that student's data, as follows: print the student's name print the student's homework print the student's quizzes print the student's tests Task 4

lloyd = { "name": "Lloyd", "homework": [90. 0, 97. 0, 75. 0, 92 lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] students = [lloyd,alice,tyler] for student in students: print (student["name"]) print (student["homework"]) print (student["quizzes"]) print (student["tests"]) Task 4 Solutions

Instructions Write a function average that takes a list of numbers and returns the average. Define a function called average that has one argument, numbers. Inside that function, call the built-in sum() function with the numbers list as a parameter. Store the result in a variable called total. Use float() to convert total and store the result in total. Divide total by the length of the numbers list. Use the built- in len() function to calculate that. Return that result. Task 5

lloyd = { "name": "Lloyd", "homework": [90. 0, 97. 0, 75. 0, 92 lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] def average(numbers): total = sum(numbers) total = float(total)/len(numbers) return(total) Task 5 Solution

Instructions Write a function called get_average that takes a student dictionary (like lloyd, alice, or tyler) as input and returns his/her weighted average. Define a function called get_average that takes one argument called student. Make a variable homework that stores the average() of student["homework"]. Repeat step 2 for "quizzes" and "tests". Multiply the 3 averages by their weights and return the sum of those three. Homework is 10%, quizzes are 30% and tests are 60% Task 6

lloyd = { "name": "Lloyd", "homework": [90. 0, 97. 0, 75. 0, 92 lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0],"tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] def average(numbers): total = sum(numbers) total = float(total)/len(numbers) return(total) def get_average(student): homework = average(student["homework"]) quizzes = average(student["quizzes"]) tests = average(student["tests"]) Sum = homework*0.1 +quizzes*0.3 +tests*0.6 return(Sum) Task 6 Solution

Instructions Define a new function called get_letter_grade that has one argument called score. Expect score to be a number. Inside your function, test score using a chain of if: / elif: / else: statements, like so: If score is 90 or above: return "A" Else if score is 80 or above: return "B" Else if score is 70 or above: return "C" Else if score is 60 or above: return "D" Otherwise: return "F" Finally, test your function! Call your get_letter_grade function with the result of get_average(lloyd). Print the resulting letter grade. Task 7

def average(numbers): total = sum(numbers) total = float(total)/len(numbers) return(total) def get_average(student): homework = average(student["homework"]) quizzes = average(student["quizzes"]) tests = average(student["tests"]) Sum = homework*0.1 +quizzes*0.3 +tests*0.6 return(Sum) def get_letter_grade(score): if score >= 90: return("A") elif score >= 80: return("B") elif score >= 70: return("C") elif score >= 60: return("D") else: return("F") average = get_average(lloyd) print(get_letter_grade(average)) Task 7 Solution

Instructions Define a function called get_class_average that has one argument students. You can expect students to be a list containing your three students. First, make an empty list called results. For each student item in the class list, calculate get_average(student) and then call results.append() with that result. Finally, return the result of calling average() with results Task 8

Task 8 Solution lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] tyler = { "name": "Tyler", "homework": [0.0, 87.0, 75.0, 22.0], "quizzes": [0.0, 75.0, 78.0], "tests": [100.0, 100.0] def average(numbers): total = sum(numbers) total = float(total)/len(numbers) return(total) def get_average(student): homework = average(student["homework"]) quizzes = average(student["quizzes"]) tests = average(student["tests"]) Sum = homework*0.1 +quizzes*0.3 +tests*0.6 return(Sum) def get_letter_grade(score): if score >= 90: return("A") elif score >= 80: return("B") elif score >= 70: return("C") elif score >= 60: return("D") else: return("F") print(get_average(lloyd)) students = [lloyd,alice,tyler] def get_class_average(students): results = [] classlist = students for student in classlist: results.append(get_average(student)) result = average(results) return(result) Task 8 Solution

Instructions Finally, print out the result of calling get_class_average with your students list. Your students should be [lloyd, alice, tyler]. Then, print the result of get_letter_grade for the class's average. Task 9

Final lines of code are: class_average = get_class_average(students) print(class_average) print(get_letter_grade(class_average)) Task 9 Solution