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.

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:
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Dictionaries: Keeping track of pairs
Python Programming Chapter 9: Tuples Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
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.
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.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 16 Dictionaries 5/10/09 Python Mini-Course: Lesson 16 1.
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.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Guide to Programming with Python
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Python Programming Chapter 8: Lists 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.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
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.
© 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.
13.1 Matrices and Their Sums
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.
Built-in Data Structures in Python An Introduction.
Iterators, Linked Lists, MapReduce, Dictionaries, and List Comprehensions... OH MY! Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 Dictionaries and Sets.
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.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
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.
7. Lists 1 Let’s Learn Saenthong School, January – February 2016 Teacher: Aj. Andrew Davison, CoE, PSU Hat Yai Campus
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.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
CS100 - PYTHON – EXAM 2 REVIEW -ONLY THE VITAL STUFF- PYTHON STRING METHODS, LOOPS, FILES, AND DICTIONARIES.
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.
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.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
Section06: Sequences Chapter 4 and 5. General Description "Normal" variables x = 19 – The name "x" is associated with a single value Sequence variables:
More Python Data Structures  Classes ◦ Should have learned in Simpson’s OOP ◦ If not, read chapters in Downey’s Think Python: Think like a Computer Scientist.
String and Lists Dr. José M. Reyes Álamo.
Intro to CS Nov 21, 2016.
Module 4 String and list – String traversal and comparison with examples, List operation with example, Tuples and Dictionaries-Operations and examples.
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
When to use Tuples instead of Lists
Arrays An array in PHP is an ordered map
Dictionaries, File operations
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Intro to Computer Science CS 1510 Dr. Sarah Diesburg
Lists in Python.
Intro to Computer Science CS 1510 Dr. Sarah Diesburg
CHAPTER THREE Sequences.
Guide to Programming with Python
Lists A list is an ordered set of values, where each value is identified by an index. The values that make up a list are called its elements. Lists are.
String and Lists Dr. José M. Reyes Álamo.
Topics Sequences Introduction to Lists List Slicing
COSC 1306 COMPUTER SCIENCE AND PROGRAMMING
CHAPTER 4: Lists, Tuples and Dictionaries
15-110: Principles of Computing
Topics Sequences Introduction to Lists List Slicing
Python Review
Dictionary.
Presentation transcript:

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 an index, you get an error. Dictionaries are similar to other compound types except that they can use any immutable type as an index

Create a Dictionary One way to create a dictionary is to start with the empty dictionary and add elements. The empty dictionary is denoted {}: >>> eng2sp = {} >>> eng2sp['one'] = 'uno' >>> eng2sp['two'] = 'dos' >>> print eng2sp – {'one': 'uno', 'two': 'dos'}

Create a Dictionary Another way to create a dictionary is to provide a list of key-value pairs using the same syntax as the previous output: >>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

Create a Dictionary The elements of a dictionary appear in a comma-separated list. Each entry contains an index and a value separated by a colon. In a dictionary, the indices are called keys, so the elements are called key-value pairs we use the keys to look up the corresponding values >>> print eng2sp['two']

Dictionary operations The del statement removes a key-value pair from a dictionary >>> inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} >>> del inventory['pears'] >>> print inventory – {'oranges': 525, 'apples': 430, 'bananas': 312} we might just change the value associated with pears: >>> inventory['pears'] = 0 >>> print inventory {'oranges': 525, 'apples': 430, 'pears': 0, 'bananas': 312}

Dictionary operations The len function also works on dictionaries; it returns the number of key-value pairs: >>> len(inventory) – 4

Dictionary methods A method is similar to a function -it takes parameters and returns a value-but the syntax is different. For example, the keys method takes a dictionary and returns a list of the keys that appear, but instead of the function syntax keys(eng2sp), we use the method syntax eng2sp.keys(). >>> eng2sp.keys() – ['one', 'three', 'two']

Dictionary methods The values method is similar; it returns a list of the values in the dictionary: >>> eng2sp.values() – ['uno', 'tres', 'dos'] The items method returns both, in the form of a list of tuples -one for each key-value pair: >>> eng2sp.items() – [('one','uno'), ('three', 'tres'), ('two', 'dos')]

Dictionary methods the method has_key takes a key and returns true (1) if the key appears in the dictionary: >>> eng2sp.has_key('one') – 1 >>> eng2sp.has_key('deux') – 0 If you try to call a method without specifying an object, you get an error. In this case, the error message is not very helpful: >>> has_key('one') – NameError: has_key

Aliasing and copying Because dictionaries are mutable, you need to be aware of aliasing If you want to modify a dictionary and keep a copy of the original, use the copy method. >>> opposites = {'up': 'down', 'right': 'wrong', 'true': 'false'} >>> alias = opposites >>> copy = opposites.copy()

Aliasing and copying alias and opposites refer to the same object; copy refers to a fresh copy of the same dictionary. If we modify alias, opposites is also changed: >>> alias['right'] = 'left' >>> opposites['right'] – 'left' If we modify copy, opposites is unchanged: >>> copy['right'] = 'privilege' >>> opposites['right'] – 'left'

Use Dictionary in Sparse matrices We can use list of lists to represent a matrix consider a sparse matrix like this one :

Use Dictionary in Sparse matrices The list representation contains a lot of zeroes: Matrix = [[0,0,0,1,0],[0,0,0,0,0],[0,2,0,0,0],[0,0,0,0,0],[0,0,0,3,0]] An alternative is to use a dictionary. For the keys, we can use tuples that contain the row and column numbers. matrix = {(0,3): 1, (2, 1): 2, (4, 3): 3}

Use Dictionary in Sparse matrices We only need three key-value pairs, one for each nonzero element of the matrix. Each key is a tuple, and each value is an integer. To access an element of the matrix, we could use the [] operator: matrix[0,3] – 1

Use Dictionary in Sparse matrices There is one problem. If we specify an element that is zero, we get an error, because there is no entry in the dictionary with that key: >>> matrix[1,3] KeyError: (1, 3) The get method solves this problem: – >>> matrix.get((0,3), 0) The ¯rst argument is the key; the second argument is the value get should return if the key is not in the dictionary:

Counting letters We can write a function that counted the number of occurrences of a letter in a string. A more general version of this problem is to form a histogram of the letters in the string, that is, how many times each letter appears. Dictionaries provide an elegant way to generate a histogram: >>> letterCounts = {} >>> for letter in "Mississippi":... letterCounts[letter] = letterCounts.get (letter, 0) >>> letterCounts

Other usage Fibonacci calculation We will review after we talk about recursive