Introduction to Computing Using Python Dictionaries: Keeping track of pairs  Class dict  Class tuple.

Slides:



Advertisements
Similar presentations
1 VBScript Session What we learn last session? Regulars Expressions. Methods and properties. How to use the object and his collections. How to create.
Advertisements

Container Types in Python
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Dictionaries: Keeping track of pairs
Guide to Programming with Python
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
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.
Dictionaries Last half of Chapter 5. Dictionary A sequence of key-value pairs – Key is usually a string or integer – Value can be any python object There.
Lecture 23 – Python dictionaries 1 COMPSCI 101 Principles of Programming.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Introduction to Computing Using Python More Built-in Container Classes  Container Class dict  Container Class set  Container Class tuple  Encoding.
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
CS 177 Week 11 Recitation Slides 1 1 Dictionaries, Tuples.
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.
Data Collections: Dictionaries CSC 161: The Art of Programming Prof. Henry Kautz 11/4/2009.
© 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.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Python Programming in Context Chapter 4. Objectives To understand Python lists To use lists as a means of storing data To use dictionaries to store associative.
Built-in Data Structures in Python An Introduction.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Storage Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
Tuples and Dictionaries Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
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.
Compsci 101.2, Fall Plan for October 29 l Review dictionaries and their use  Very efficient, easy to use  Efficiency doesn't matter much for.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
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.
COSC 1306—COMPUTER SCIENCE AND PROGRAMMING PYTHON TUPLES, SETS AND DICTIONARIES Jehan-François Pâris
Dictionaries Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Dictionaries Intro to Computer Science CS 1510 Dr. Sarah Diesburg.
Introduction to Python Aug 22, 2013 Hee-gook Jun.
Introduction to Arrays. Learning Objectives By the end of this lecture, you should be able to: – Understand what an array is – Know how to create an array.
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
Dictionaries Ruth Anderson UW CSE 160 Winter
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.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
Section06: Sequences Chapter 4 and 5. General Description "Normal" variables x = 19 – The name "x" is associated with a single value Sequence variables:
10 - Python Dictionary John R. Woodward.
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
Containers and Lists CIS 40 – Introduction to Programming in Python
CSc 120 Introduction to Computer Programing II
Announcements Project 4 due Wed., Nov 7
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Ruth Anderson CSE 140 University of Washington
Intro to Computer Science CS 1510 Dr. Sarah Diesburg
Intro to Computer Science CS 1510 Dr. Sarah Diesburg
CHAPTER THREE Sequences.
Guide to Programming with Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
COSC 1306 COMPUTER SCIENCE AND PROGRAMMING
Introduction to Dictionaries
Ruth Anderson UW CSE 160 Winter 2017
Dictionaries Dictionary: object that stores a collection of data
Python Primer 1: Types and Operators
Michael Ernst CSE 140 University of Washington
Nate Brunelle Today: Dictionaries
Dictionaries: Keeping track of pairs
CHAPTER 4: Lists, Tuples and Dictionaries
Ruth Anderson CSE 160 University of Washington
Ruth Anderson UW CSE 160 Spring 2018
Winter 2019 CISC101 5/26/2019 CISC101 Reminders
Dictionary.
Tuple.
Introduction to Computer Science
Ruth Anderson UW CSE 160 Winter 2016
Presentation transcript:

Introduction to Computing Using Python Dictionaries: Keeping track of pairs  Class dict  Class tuple

Introduction to Computing Using Python The dictionary: An associative data type  Many things in the world come in pairs, where Thing 1 is associated with Thing 2. For example  A word and its definition  A person and the person's birthday  A living thing and its species  The Python class dictionary models such relationships flexibly and efficiently >>> definitions = {'modest':'unassuming', 'eat':'chew and swallow'} >>> bdays = {'Napoleon':'15 Aug 1769', 'Lady Gaga':'Mar '} >>> species = {'Fido':'dog', 'Finny':'catfish', 'Pepe Le Pew':'skunk'}

Introduction to Computing Using Python Dictionary: Syntax and types  This is the syntax of a dictionary:  A dictionary is enclosed in curly brackets. The empty dictionary is denoted {}.  A dictionary is a set of key:value pairs. Each key and its value are separated by a colon (':').  Key:value pairs are separated by commas.  Permitted types of keys and values:  A key can be any immutable type – for example, a string, a number or a tuple. A key cannot be a mutable type, such as a list.  A dictionary may contain keys of different types, but...  Each key in a dictionary must be unique  A value can be any type we have learned – a string, a number, a list – even another dictionary.

Introduction to Computing Using Python Dictionary: Basic operations >>> # create an empty dictionary >>> d = {} >>> # add a key:value pair, using index and assignment operators >>> d['NJIT'] = 'tech' >>> # look up the value of a key using the index ([]) operator >>> d['NJIT'] 'tech' >>> # change a value by assigning a new value >>> d['NJIT'] = 'tech school' >>> d['NJIT'] 'tech school' >>> # remove a key:value pair and return its value >>> njitSchoolType = d.pop('NJIT') >>> njitSchoolType 'tech school' >>> d {}

Introduction to Computing Using Python Dictionary: More things you can do >>> # find the size (number of key:value pairs) of a dictionary >>> d = {1:'for the money', 'two':'for the show'} >>> len(d) 2 >>> # test for the membership (presence) of a key >>> 1 in d True >>> 2 in d False >>> # incorporate dictionary d2 into dictionary d >>> d2 = {'Twain':'Mark'} >>> d.update(d2) >>> d {1: 'for the money', 'Twain': 'Mark', 'two': 'for the show'} >>> # note that dictionary d2 is not changed >>> d2 {'Twain':'Mark'}

Introduction to Computing Using Python Dictionary properties: Order and speed  The order that a dictionary stores keys is not guaranteed >>> d = {1:'for the money', 'two':'for the show'} >>> d2 = {'Twain':'Mark'} >>> d.update(d2) >>> d {1: 'for the money', 'Twain': 'Mark', 'two': 'for the show'} Note that the key:value pair 'Twain':'Mark' from d2 has been inserted between the pairs already in d  Dictionary lookup (amazingly!) does not get slower as the dictionary gets bigger Inserting ten million elements may take a few seconds >>> d = {} >>> for i in range( ): d[i] = str(i) Retrieving one element from among 10,000,000 is immediate >>> d[ ] ' '

Introduction to Computing Using Python Iterating over a dictionary  Iterate over dictionary keys like this >>> # Use the dictionary method d.keys() >>> d = {'tree':'oak', 'fish':'guppy', 'dog':'boxer', 'cat':'tabby'} >>> for thing in d.keys(): if 't' in thing: print(thing, end=' ') cat tree Note: for thing in d: is the same as for thing in d.keys()  Iterate over dictionary values like this Use the dictionary method d.values() >>> for value in d.values(): if 'y' in value: print(value, end=' ') guppy tabby

Introduction to Computing Using Python The tuple as a dictionary key  A tuple is almost the same as a list, except that it is immutable. A tuple is delimited by parentheses where a list has square brackets This is a list of int's >>> intList = [1, 2, 3] Attempting to use a list as a key will result in an error >>> d = {intList: "some int's"} Traceback (most recent call last): File " ", line 1, in d = {intList:"some int's"} TypeError: unhashable type: 'list' Solution: Use a tuple as a key instead >>> intTuple = (1, 2, 3) # or intTuple = tuple(intList) >>> d = {intTuple: "some int's"} >>> d {(1, 2, 3): "some int's"}

Introduction to Computing Using Python Example: Keeping count(s) >>> grades = [95, 96, 100, 85, 95, 90, 95, 100, 100] Problem: you want to count how many times each item in a list occurs, but you don't know the items in advance. For example, for this list Complications: until you see the list, you don't know what counters to create you'd like to be able to access the count of an item via the item itself Solution: create a dictionary in which each distinct item is a key and its count is the associated value a good solution might look like this

Introduction to Computing Using Python A dictionary as a collection of counters def frequency(itemList): '''Compute the frequency of each item in itemList. Return the result as a dictionary in which each distinct item in itemList is a key and the item's frequency (count) is the associated value.''' counters = {} for item in itemList: # if the item hasn't been seen before if item not in counters: # add the item to the dictionary # and set its count to 1 counters[item] = 1 # otherwise, increment the count of item else: counters[item] += 1 return counters def frequency(itemList): '''Compute the frequency of each item in itemList. Return the result as a dictionary in which each distinct item in itemList is a key and the item's frequency (count) is the associated value.''' counters = {} for item in itemList: # if the item hasn't been seen before if item not in counters: # add the item to the dictionary # and set its count to 1 counters[item] = 1 # otherwise, increment the count of item else: counters[item] += 1 return counters

Introduction to Computing Using Python A dictionary as a collection of lists wordOccurrences = [('rabbbit',1),('Alice',1), ('rabbbit',4),('Alice',7),('Alice',10)] def makeIndex(wordPageList): '''Given a list of word/page tuples, compute and return an index of the pages on which words occur.''' wordIndex = {} for item in wordPageList: word = item[0]; page = item[1] # if the word hasn't been seen before if word not in wordIndex: # add the word to the dictionary wordIndex[word] = [page] # otherwise, add the page else: wordIndex[word].append(page) return wordIndex aliceIndex = makeIndex(wordOccurrences) # Returns {'rabbbit': [1, 4], 'Alice': [1, 7, 10]} wordOccurrences = [('rabbbit',1),('Alice',1), ('rabbbit',4),('Alice',7),('Alice',10)] def makeIndex(wordPageList): '''Given a list of word/page tuples, compute and return an index of the pages on which words occur.''' wordIndex = {} for item in wordPageList: word = item[0]; page = item[1] # if the word hasn't been seen before if word not in wordIndex: # add the word to the dictionary wordIndex[word] = [page] # otherwise, add the page else: wordIndex[word].append(page) return wordIndex aliceIndex = makeIndex(wordOccurrences) # Returns {'rabbbit': [1, 4], 'Alice': [1, 7, 10]}