Dictionaries Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Input and Output Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Dictionaries: Keeping track of pairs
Tuples Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Guide to Programming with Python
Python for Informatics: Exploring Information
9 Dictionaries © 2010 David A Watt, University of Glasgow Accelerated Programming 2 Part I: Python Programming 1.
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.
INLS 560 – D ICTIONARIES Instructor: Jason Carter.
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.
COMPSCI 101 Principles of Programming Lecture 24 – Using dictionaries to manage a small file of information.
CSci 143 Sets & Maps Adapted from Marty Stepp, University of Washington
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Lecture 23 – Python dictionaries 1 COMPSCI 101 Principles of Programming.
 1 String and Data Processing. Sequential Processing Processing each element in a sequence for e in [1,2,3,4]: print e for c in “hello”: print c for.
Tutorial 10 Dictionaries and Classes. Reminder Assignment 09 is due April 6 at 11:55pm (last day of classes) Next tutorial is on April 6 (Monday)
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.
Data Collections: Dictionaries CSC 161: The Art of Programming Prof. Henry Kautz 11/4/2009.
Nanotech Example Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 14 Tuples, Sets, and Dictionaries 1.
Beyond Lists: Other Data Structures CS303E: Elements of Computers and Programming.
LECTURE 36: DICTIONARY CSC 212 – Data Structures.
Recap form last time How to do for loops map, filter, reduce Next up: dictionaries.
Interface and Implementation Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Storage Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 Dictionaries and Sets.
CS261 Data Structures Maps (or Dictionaries). Goals Introduce the Map(or Dictionary) ADT Introduce an implementation of the map with a Dynamic Array.
Lists Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
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.
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.
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
Exceptions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Strings 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.
CSC 4630 Meeting 17 March 21, Exam/Quiz Schedule Due to ice, travel, research and other commitments that we all have: –Quiz 2, scheduled for Monday.
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.
CSE 143 Lecture 11: Sets and Maps reading:
CSC 4630 Perl 3 adapted from R. E. Beck. Problem But we worked on it first: Input: Read from a text file named in a command line argument Output: List.
CPSC 252 Tables / Maps / Dictionaries Page 1 Tables, Maps and Dictionaries A table (or map or dictionary) is a collection of key/value pairs. In general.
CompSci 101 Introduction to Computer Science March 24, 2016 Prof. Rodger compsci 101, spring
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.
Intro to CS Nov 21, 2016.
Python Aliasing Copyright © Software Carpentry 2010
CSc 110, Spring 2017 Lecture 29: Sets and Dictionaries
Sets and Dictionaries Examples Copyright © Software Carpentry 2010
Containers and Lists CIS 40 – Introduction to Programming in Python
C++ Standard Library.
Announcements Project 4 due Wed., Nov 7
Data types: Complex types (Dictionaries)
Lecture 10 Data Collections
CSc 110, Spring 2018 Lecture 32: Sets and Dictionaries
CSc 110, Autumn 2017 Lecture 30: Sets and Dictionaries
COSC 1323 – Computer Science Concepts I
Sets (11.2) set: A collection of unique values (no duplicates allowed) that can perform the following operations efficiently: add, remove, search (contains)
Guide to Programming with Python
Introduction to Dictionaries
Input and Output with FILES
CS 1111 Introduction to Programming Fall 2018
Dictionaries Dictionary: object that stores a collection of data
Sets (11.2) set: A collection of unique values (no duplicates allowed) that can perform the following operations efficiently: add, remove, search (contains)
Dictionaries: Keeping track of pairs
Python for Informatics: Exploring Information
CSE 231 Lab 9.
Dictionary.
Presentation transcript:

Dictionaries Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See for more information. Sets and Dictionaries

Dictionaries Back to the data from our summer counting birds in a mosquito-infested swamp in northern Ontario

Sets and DictionariesDictionaries Back to the data from our summer counting birds in a mosquito-infested swamp in northern Ontario How many birds of each kind did we see?

Sets and DictionariesDictionaries Back to the data from our summer counting birds in a mosquito-infested swamp in northern Ontario How many birds of each kind did we see? Input is a list of several thousand bird names

Sets and DictionariesDictionaries Back to the data from our summer counting birds in a mosquito-infested swamp in northern Ontario How many birds of each kind did we see? Input is a list of several thousand bird names Output is a list of names and counts

Sets and DictionariesDictionaries Could use a list of [name, count] pairs

Sets and DictionariesDictionaries Could use a list of [name, count] pairs def another_bird(counts, bird_name): for i in range(len(counts)): if counts[i][0] == bird_name: counts[i][1] += 1 return counts.append([bird_name, 1])

Sets and DictionariesDictionaries Could use a list of [name, count] pairs def another_bird(counts, bird_name): for i in range(len(counts)): if counts[i][0] == bird_name: counts[i][1] += 1 return counts.append([bird_name, 1]) List of pairs

Sets and DictionariesDictionaries Could use a list of [name, count] pairs def another_bird(counts, bird_name): for i in range(len(counts)): if counts[i][0] == bird_name: counts[i][1] += 1 return counts.append([bird_name, 1]) Name to add

Sets and DictionariesDictionaries Could use a list of [name, count] pairs def another_bird(counts, bird_name): for i in range(len(counts)): if counts[i][0] == bird_name: counts[i][1] += 1 return counts.append([bird_name, 1) Look at each pair already in the list

Sets and DictionariesDictionaries Could use a list of [name, count] pairs def another_bird(counts, bird_name): for i in range(len(counts)): if counts[i][0] == bird_name: counts[i][1] += 1 return counts.append([bird_name, 1]) If this is the bird we're looking for…

Sets and DictionariesDictionaries Could use a list of [name, count] pairs def another_bird(counts, bird_name): for i in range(len(counts)): if counts[i][0] == bird_name: counts[i][1] += 1 return counts.append([bird_name, 1]) …add 1 to its count and finish

Sets and DictionariesDictionaries Could use a list of [name, count] pairs def another_bird(counts, bird_name): for i in range(len(counts)): if counts[i][0] == bird_name: counts[i][1] += 1 return counts.append([bird_name, 1]) Otherwise, add a new pair to the list

Sets and DictionariesDictionaries Could use a list of [name, count] pairs def another_bird(counts, bird_name): for i in range(len(counts)): if counts[i][0] == bird_name: counts[i][1] += 1 return counts.append([bird_name, 1]) Pattern: handle an existing case and return in loop, or take default action if we exit the loop normally

Sets and DictionariesDictionaries Could use a list of [name, count] pairs def another_bird(counts, bird_name): for i in range(len(counts)): if counts[i][0] == bird_name: counts[i][1] += 1 return counts.append([bird_name, 1]) start []

Sets and DictionariesDictionaries Could use a list of [name, count] pairs def another_bird(counts, bird_name): for i in range(len(counts)): if counts[i][0] == bird_name: counts[i][1] += 1 return counts.append([bird_name, 1]) start [] loon [['loon', 1]]

Sets and DictionariesDictionaries Could use a list of [name, count] pairs def another_bird(counts, bird_name): for i in range(len(counts)): if counts[i][0] == bird_name: counts[i][1] += 1 return counts.append([bird_name, 1]) start [] loon [['loon', 1]] goose [['loon', 1], ['goose', 1]]

Sets and DictionariesDictionaries Could use a list of [name, count] pairs def another_bird(counts, bird_name): for i in range(len(counts)): if counts[i][0] == bird_name: counts[i][1] += 1 return counts.append([bird_name, 1]) start [] loon [['loon', 1]] goose [['loon', 1], ['goose', 1]] loon [['loon', 2], ['goose', 1]]

Sets and DictionariesDictionaries There's a better way

Sets and DictionariesDictionaries There's a better way Use a dictionary

Sets and DictionariesDictionaries There's a better way Use a dictionary An unordered collection of key/value pairs

Sets and DictionariesDictionaries There's a better way Use a dictionary An unordered collection of key/value pairs Like set elements, keys are:

Sets and DictionariesDictionaries There's a better way Use a dictionary An unordered collection of key/value pairs Like set elements, keys are: - Immutable

Sets and DictionariesDictionaries There's a better way Use a dictionary An unordered collection of key/value pairs Like set elements, keys are: - Immutable - Unique

Sets and DictionariesDictionaries There's a better way Use a dictionary An unordered collection of key/value pairs Like set elements, keys are: - Immutable - Unique - Not stored in any particular order

Sets and DictionariesDictionaries There's a better way Use a dictionary An unordered collection of key/value pairs Like set elements, keys are: - Immutable - Unique - Not stored in any particular order No restrictions on values

Sets and DictionariesDictionaries There's a better way Use a dictionary An unordered collection of key/value pairs Like set elements, keys are: - Immutable - Unique - Not stored in any particular order No restrictions on values - Don't have to be immutable or unique

Sets and DictionariesDictionaries Create a dictionary by putting key:value pairs in {}

Sets and DictionariesDictionaries >>> birthdays = {'Newton' : 1642, 'Darwin' : 1809} Create a dictionary by putting key:value pairs in {}

Sets and DictionariesDictionaries >>> birthdays = {'Newton' : 1642, 'Darwin' : 1809} Create a dictionary by putting key:value pairs in {} Retrieve values by putting key in []

Sets and DictionariesDictionaries >>> birthdays = {'Newton' : 1642, 'Darwin' : 1809} Create a dictionary by putting key:value pairs in {} Retrieve values by putting key in [] Just like indexing strings and lists

Sets and DictionariesDictionaries >>> birthdays = {'Newton' : 1642, 'Darwin' : 1809} Create a dictionary by putting key:value pairs in {} >>> print birthdays['Newton'] 1642 Retrieve values by putting key in [] Just like indexing strings and lists

Sets and DictionariesDictionaries >>> birthdays = {'Newton' : 1642, 'Darwin' : 1809} Create a dictionary by putting key:value pairs in {} >>> print birthdays['Newton'] 1642 Retrieve values by putting key in [] Just like indexing strings and lists Just like using a phonebook or dictionary

Sets and DictionariesDictionaries Add another value by assigning to it

Sets and DictionariesDictionaries >>> birthdays['Turing'] = 1612 # that's not right Add another value by assigning to it

Sets and DictionariesDictionaries >>> birthdays['Turing'] = 1612 # that's not right Add another value by assigning to it Overwrite value by assigning to it as well

Sets and DictionariesDictionaries >>> birthdays['Turing'] = 1612 # that's not right Add another value by assigning to it >>> birthdays['Turing'] = 1912 >>> print birthdays {'Turing' : 1912, 'Newton' : 1642, 'Darwin' : 1809} Overwrite value by assigning to it as well

Sets and DictionariesDictionaries Note: entries are not in any particular order

Sets and DictionariesDictionaries 'Turing' 'Newton' 'Darwin' Note: entries are not in any particular order

Sets and DictionariesDictionaries Key must be in dictionary before use

Sets and DictionariesDictionaries >>> birthdays['Nightingale'] KeyError: 'Nightingale' Key must be in dictionary before use

Sets and DictionariesDictionaries >>> birthdays['Nightingale'] KeyError: 'Nightingale' Key must be in dictionary before use Test whether key is present using in

Sets and DictionariesDictionaries >>> birthdays['Nightingale'] KeyError: 'Nightingale' Key must be in dictionary before use >>> 'Nightingale' in birthdays False >>> 'Darwin' in birthdays True Test whether key is present using in

Sets and DictionariesDictionaries Use for to loop over keys

Sets and DictionariesDictionaries Use for to loop over keys Unlike lists, where for loops over values

Sets and DictionariesDictionaries >>> for name in birthdays:... print name, birthdays[name] Turing 1912 Newton 1642 Darwin 1809 Use for to loop over keys Unlike lists, where for loops over values

Sets and DictionariesDictionaries Let's count those birds

Sets and DictionariesDictionaries import sys if __name__ == '__main__': reader = open(sys.argv[1], 'r') lines = reader.readlines() reader.close() count = count_names(lines) for name in count: print name, count[name] Let's count those birds

Sets and DictionariesDictionaries import sys if __name__ == '__main__': reader = open(sys.argv[1], 'r') lines = reader.readlines() reader.close() count = count_names(lines) for name in count: print name, count[name] Let's count those birds Read all the data

Sets and DictionariesDictionaries import sys if __name__ == '__main__': reader = open(sys.argv[1], 'r') lines = reader.readlines() reader.close() count = count_names(lines) for name in count: print name, count[name] Let's count those birds Count distinct values

Sets and DictionariesDictionaries import sys if __name__ == '__main__': reader = open(sys.argv[1], 'r') lines = reader.readlines() reader.close() count = count_names(lines) for name in count: print name, count[name] Let's count those birds Show results

Sets and DictionariesDictionaries def count_names(lines): '''Count unique lines of text, returning dictionary.''' result = {} for name in lines: name = name.strip() if name in result: result[name] = result[name] + 1 else: result[name] = 1 return result

Sets and DictionariesDictionaries def count_names(lines): '''Count unique lines of text, returning dictionary.''' result = {} for name in lines: name = name.strip() if name in result: result[name] = result[name] + 1 else: result[name] = 1 return result Explain what we're doing to the next reader

Sets and DictionariesDictionaries def count_names(lines): '''Count unique lines of text, returning dictionary.''' result = {} for name in lines: name = name.strip() if name in result: result[name] = result[name] + 1 else: result[name] = 1 return result Create an empty dictionary to fill

Sets and DictionariesDictionaries def count_names(lines): '''Count unique lines of text, returning dictionary.''' result = {} for name in lines: name = name.strip() if name in result: result[name] = result[name] + 1 else: result[name] = 1 return result Handle input values one at a time

Sets and DictionariesDictionaries def count_names(lines): '''Count unique lines of text, returning dictionary.''' result = {} for name in lines: name = name.strip() if name in result: result[name] = result[name] + 1 else: result[name] = 1 return result Clean up before processing

Sets and DictionariesDictionaries def count_names(lines): '''Count unique lines of text, returning dictionary.''' result = {} for name in lines: name = name.strip() if name in result: result[name] = result[name] + 1 else: result[name] = 1 return result If we have seen this value before…

Sets and DictionariesDictionaries def count_names(lines): '''Count unique lines of text, returning dictionary.''' result = {} for name in lines: name = name.strip() if name in result: result[name] = result[name] + 1 else: result[name] = 1 return result …add one to its count

Sets and DictionariesDictionaries def count_names(lines): '''Count unique lines of text, returning dictionary.''' result = {} for name in lines: name = name.strip() if name in result: result[name] = result[name] + 1 else: result[name] = 1 return result But if it's the first time we have seen this name, store it with a count of 1

Sets and DictionariesDictionaries def count_names(lines): '''Count unique lines of text, returning dictionary.''' result = {} for name in lines: name = name.strip() if name in result: result[name] = result[name] + 1 else: result[name] = 1 return result Return the result

Sets and DictionariesDictionaries Counter in action

Sets and DictionariesDictionaries Counter in action start {}

Sets and DictionariesDictionaries Counter in action start {} loon {'loon' : 1}

Sets and DictionariesDictionaries Counter in action start {} loon {'loon' : 1} goose {'loon' : 1, 'goose' : 1}

Sets and DictionariesDictionaries Counter in action start {} loon {'loon' : 1} goose {'loon' : 1, 'goose' : 1} loon {'loon' : 2, 'goose' : 1}

Sets and DictionariesDictionaries Counter in action start {} loon {'loon' : 1} goose {'loon' : 1, 'goose' : 1} loon {'loon' : 2, 'goose' : 1} But like sets, dictionaries are much more efficient than lookup lists

July 2010 created by Greg Wilson Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See for more information.