CS 177 Week 11 Recitation Slides 1 1 Dictionaries, Tuples.

Slides:



Advertisements
Similar presentations
Course A201: Introduction to Programming 10/28/2010.
Advertisements

Dictionaries: Keeping track of pairs
Guide to Programming with Python
Fundamentals of Python: From First Programs Through Data Structures
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
Python Dictionary.
Sequences The range function returns a sequence
COMPSCI 101 Principles of Programming Lecture 24 – Using dictionaries to manage a small file of information.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 6: Lists, Tuples, and Dictionaries – Exercises Xiang Lian The University of Texas – Pan American Edinburg,
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Lecture 23 – Python dictionaries 1 COMPSCI 101 Principles of Programming.
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
Announcements All groups have been assigned Homework: By this evening everyone in your group and set up a meeting time to discuss project 4 Project.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 14 Tuples, Sets, and Dictionaries 1.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
Beyond Lists: Other Data Structures CS303E: Elements of Computers and Programming.
Built-in Data Structures in Python An Introduction.
Recap form last time How to do for loops map, filter, reduce Next up: dictionaries.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Tuples and Dictionaries Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Python Data Structures CMSC 201. Built in Types Today we will be talking about some other built in types in python! Tuples Sets Dictionaries.
14. DICTIONARIES AND SETS Rocky K. C. Chang 17 November 2014 (Based on from Charles Dierbach, Introduction to Computer Science Using Python and Punch and.
Introduction to Computing Using Python Dictionaries: Keeping track of pairs  Class dict  Class tuple.
Data Collections CS 127. Lists Lists are ordered sequences of items All programming languages provide a sequence structure similar to a Python list; in.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
CSC Introduction to Data Structures Devon M. Simmonds Computer Science Department University of North Carolina Wilmington Wilmington, NC 28403
LECTURE 3 Python Basics Part 2. FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for.
Dictionaries Ruth Anderson CSE 160 University of Washington 1.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
7. Lists 1 Let’s Learn Saenthong School, January – February 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus
COSC 1306—COMPUTER SCIENCE AND PROGRAMMING PYTHON TUPLES, SETS AND DICTIONARIES Jehan-François Pâris
Dictionaries Intro to Computer Science CS 1510 Dr. Sarah Diesburg.
Python Data Structures By Greg Felber. Lists An ordered group of items Does not need to be the same type – Could put numbers, strings or donkeys in the.
Magic 8 ball. "Design and write a python program that emulates a Magic Eight Ball. Your program should continually prompt the user to enter a question.
Dictionaries. The compound types you have learned about - - strings, lists, and tuples – use integers as indices. If you try to use any other type as.
Python Sets and Dictionaries Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Set properties What is a set? A set is a mutable.
Dictionaries Ruth Anderson UW CSE 160 Winter
CS2910 Week 6, Lab Today Dictionaries in Python SE-2811 Slide design: Dr. Mark L. Hornick Content: Dr. Hornick Errors: Dr. Yoder 1.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Dictionaries Alexandra Stefan CSE1310 – University of Texas at Arlington.
Intro to CS Nov 21, 2016.
10 - Python Dictionary John R. Woodward.
Python Variable Types.
Tuples and Lists.
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
When to use Tuples instead of Lists
Chapter 4 Strings & Tuples
loops for loops iterate over a given sequence.
Department of Computer Science,
Announcements Project 4 due Wed., Nov 7
Data types: Complex types (Dictionaries)
Ruth Anderson UW CSE 160 Spring 2018
Intro to Computer Science CS 1510 Dr. Sarah Diesburg
Intro to Computer Science CS 1510 Dr. Sarah Diesburg
Bryan Burlingame Halloween 2018
CS190/295 Programming in Python for Life Sciences: Lecture 6
4. sequence data type Rocky K. C. Chang 16 September 2018
CS 1111 Introduction to Programming Fall 2018
Dictionaries Dictionary: object that stores a collection of data
COSC 1306 COMPUTER SCIENCE AND PROGRAMMING
Dictionaries: Keeping track of pairs
15-110: Principles of Computing
Bryan Burlingame Halloween 2018
Introduction to Dictionaries
Dictionary basics Consider typing the word “infinite” in the Google search:
Dictionary.
Tuple.
Introduction to Computer Science
Presentation transcript:

CS 177 Week 11 Recitation Slides 1 1 Dictionaries, Tuples

Announcements 2 2

Why Do We Use Dictionary 1/3 Suppose we have the following table, that associates an identifier to a student name: This association is a relationship between the identifier and the student name 33 StudentIDStudentName S1Kate S2Brittany S3Alice

Why Do We Use Dictionary 2/3 Can we represent this relationship using lists? Yes, we can. Look at the following: – myList = [[‘S1’, ‘Kate’], [‘S2’, ‘Brittany’], [‘S3’, ‘Alice’]] – However, we have to access the elements of the list above by using integer indexes: – >>> myList[0] – ['S1', 'Kate'] – >>> myList[0][1] – 'Kate‘ – >>> myList[0][0] – 'S1' CS177 - Spring /18/2015

Why Do We Use Dictionary 3/3 But we can not “ask” our Python list: please give me back the name of the student associated to the identifier ‘S1’ If we need to do that, we have to use a new Python construct: the dictionary CS177 - Spring /18/2015

Using Dictionaries in Python 6 Python dictionaries store data element as a pairs of key/value data in the form of key:value “associative lists” surrounded by { }, rather than [ ] in lists KEY VALUE 6 StudentIDStudentName S1Kate S2Brittany S3Alice

Creating Dictionaries 7 We can store the data in the above table by using python dictionary as follows >>> StuDict = {‘S1’:‘Kate’, ‘S2’:‘Brittany’, ‘S3’:‘Alice’} We can also do the following, >>> StuDict = {} >>> StuDict[‘S1’] = ‘Kate’ >>> StuDict[‘S2’] = ‘Brittany’ >>> StuDict[‘S3’] = ‘Alice’ 7

Creating Dictionaries 8 We can also create a dictionary from a list >>> myList = [[‘S1’, ‘Kate’], [‘S2’, ‘Brittany’], [‘S3’, ‘Alice’]] >>> StuDict = dict(myList) >>> mydict {'S3': 'Alice', 'S2': 'Brittany', 'S1': 'Kate'} 8

KEY in Dictionary vs. INDEX in List 99 Type – Key (dictionary): Any immutable type, usually strings or integers – Index (list): Integers An example of a string used as a dictionary key >>> StuDict = {'S1':'Kate', 'S2':'Brittany', 'S3':'Alice'} >>>print (StuDict['S1']) ‘Kate’ An example of an integer used as a dictionary key >>> StuDict = {1:'Kate', 2:'Brittany', 3:'Alice'} >>>print (StuDict[1]) ‘Kate’

KEY in Dictionary vs. INDEX in List 10 Definition – Key (dictionary): specified by users, not based on ordering – Index (list): provided by system, implicitly based on list ordering Example – Dictionary works without ordering >>> StuDict = {‘S1’:‘Kate’, ‘S2’:‘Brittany’, ‘S3’:‘Alice’} >>>print StuDict[‘S3’] ‘Kate’ >>> StuDict = {‘S3’:‘Kate’, ‘S2’:‘Brittany’, ‘S1’:‘Alice’} >>>print StuDict[‘S3’] ‘Kate’ – List works with implicit ordering: >>>StudList = [[‘S1’, ‘Kate’], [‘S2’, ‘Brittany’], [‘S3’, ‘Alice’]] – We cannot change element’s index in a list

Dictionary Operations 11 >>> inventory = {'pears': 217, 'apples': 430, 'oranges': 525, 'bananas': 312} Getting an element from the dictionary >>> inventory['oranges'] 525 Remove the entry from the dictionary >>> del inventory['pears'] >>> print(inventory) {'apples': 430, 'oranges': 525, 'bananas': 312}

Dictionary Operations 12 The len function also works on dictionaries; it returns the number of key-value pairs: >>> len(inventory) 3

Dictionary Methods 13 Getting all keys of a dictionary >>> list(inventory.keys()) ['oranges', 'apples', 'pears', 'bananas'] Getting all values from a dictionary >>> list(inventory.values()) [525, 430, 217, 312]

Dictionaries and for loops 14 >>> for key in inventory: print("Value : ", inventory[key]) Value : 525 Value : 430 Value : 217 Value : 312

Dictionary Example 15 def readFile(): file = open("names.txt", "r") contents = file.read() file.close() lines = contents.split("\n") phonebook = {} for line in lines: items = line.split(":") phonebook[items[0]] = items[1] return phonebook

Dictionary Example 16 def findPhoneNumber(name): phonebook = readFile() for key in phonebook: if(key.lower().find(name.lower()) != -1): print("Phone number for ", key, " is", phonebook[key]) >>> findPhoneNumber('parsoN') Phone number for Andrew Parson is >>>

Populating Dictionaries We can populate dictionaries with list >>>dict([(x, chr(x+97)) for x in range(10)]) {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h', 8: 'i', 9: 'j'} 17

Tuples A tuple consists of a number of values separated by commas, surrounded by ()  (x, y) coordinate pairs  Student records in the database 18

Constructing Tuples We construct a tuple corresponding to each row of the following table: >>>Tup1 = (‘S1’, ‘Kate’) >>>Tup2 = (‘S2’, ‘Brittany’) >>>Tup3 = (‘S3’, ‘Alice’) We can also build a tuple of tuples… >>>StuTup = (Tup1, Tup2, Tup3) >>>print (StuTup) ((‘S1’, ‘Kate’), (‘S2’, ‘Brittany’), (‘S3’, ‘Alice’)) 19 StudentIDStudentName S1Kate S2Brittany S3Alice

Constructing Tuples Getting an element of a Tuple in the same way we get an element of a list: >>> StuTup[1] ('S2', 'Brittany') >>> StuTup[1][0] 'S2' >>> StuTup[1][1] 'Brittany' Tuples are immutable >>>StuTup[0] = ((‘S5’, ‘Jane’)) error message -- no assignment 20

Tuple Assignment A tuple of variables on the left can be assigned values from a tuple on the right: >>> a = 10 >>> b = 20 >>> (a, b) = (b, a) >>> a 20 >>> b 10 Number of variables on the left and the number of values on the right must be the same! >>> (a, b, c, d) = (1, 2, 3) ValueError: need more than 3 values to unpack 21

Tuples as Return Values def function(a, b): sum = a + b product = a * b return(sum, product) >>> (a, b) = function(10, 20) >>> a 30 >>> b 200 >>> result = function(50, 100) >>> result[1] 5000 >>> result[0]

Now Creating a Dictionary from a List of Tuples Given a list of tuples as follows [(‘S1’, ‘Kate’), (‘S2’, ‘Brittany’), (‘S3’, ‘Alice’)] Let’s create a dictionary with the dict function dict([(‘S1’, ‘Kate’), (‘S2’, ‘Brittany’), (‘S3’, ‘Alice’)]) A tuple in the list is a pair of key:value data in the dictionary >>> dict([(‘S1’, ‘Kate’), (‘S2’, ‘Brittany’), (‘S3’, ‘Alice’)]) {‘S1’:‘Kate’, ‘S2’:‘Brittany’, ‘S3’:‘Alice’} 23

QUESTIONS? 24