Dictionaries Ruth Anderson UW CSE 160 Winter 2016 1.

Slides:



Advertisements
Similar presentations
Dictionaries (aka hash tables or hash maps) Genome 559: Introduction to Statistical and Computational Genomics Prof. James H. Thomas.
Advertisements

ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Container Types in Python
Variables and References in Python. "TAGAGAATTCTA” Objects s Names References >>> s = “TAGAGAATTCTA” >>>
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
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.
An Introduction to Python – Part II Dr. Nancy Warter-Perez.
COMPSCI 101 Principles of Programming Lecture 24 – Using dictionaries to manage a small file of information.
Data Structures UW CSE 190p Summer >>> xs = range(3) >>> xs = [1,2,3] >>> xs = [‘a’,’b’,’c’] >>> xs = [1, ‘a’, 3] >>> xs = [[1,2,3], [‘a’,’b’,’c’]]
Lecture 23 – Python dictionaries 1 COMPSCI 101 Principles of Programming.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
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.
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.
UW CSE 190p Section 8/2, Summer 2012 Dun-Yu Hsiao.
Beyond Lists: Other Data Structures CS303E: Elements of Computers and Programming.
Built-in Data Structures in Python An Introduction.
Introduction to Python and programming Ruth Anderson UW CSE 140 Winter
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 Dictionaries and Sets.
Collections Michael Ernst CSE 190p University of Washington.
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.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
Dictionaries Ruth Anderson CSE 160 University of Washington 1.
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.
Control flow Ruth Anderson UW CSE 160 Winter
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Dictionaries Alexandra Stefan CSE1310 – University of Texas at Arlington.
10 - Python Dictionary John R. Woodward.
Sharing, mutability, and immutability
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
Python – May 18 Quiz Relatives of the list: Tuple Dictionary Set
Computer Programming Fundamentals
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
List comprehensions (and other shortcuts) UW CSE 160 Winter 2017.
Ruth Anderson CSE 140 University of Washington
Sharing, mutability, and immutability
Ruth Anderson UW CSE 160 Spring 2018
Ruth Anderson UW CSE 160 Spring 2018
Ruth Anderson UW CSE 160 Winter 2017
CISC101 Reminders Quiz 2 this week.
Ruth Anderson UW CSE 160 Winter 2017
Sharing, mutability, and immutability
Ruth Anderson University of Washington CSE 160 Winter 2017
Sharing, mutability, and immutability
4. sequence data type Rocky K. C. Chang 16 September 2018
Ruth Anderson UW CSE 140 Winter 2014
Sharing, mutability, and immutability
COSC 1306 COMPUTER SCIENCE AND PROGRAMMING
Ruth Anderson UW CSE 160 Winter 2017
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
Dictionaries Dictionary: object that stores a collection of data
Sharing, mutability, and immutability
Michael Ernst CSE 140 University of Washington
Michael Ernst CSE 140 University of Washington
6. Dictionaries and sets Rocky K. C. Chang 18 October 2018
Dictionaries: Keeping track of pairs
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
Ruth Anderson CSE 160 University of Washington
Ruth Anderson UW CSE 160 Spring 2018
Dictionary.
Introduction to Computer Science
Ruth Anderson UW CSE 160 Winter 2016
Presentation transcript:

Dictionaries Ruth Anderson UW CSE 160 Winter

Dictionaries or mappings A dictionary maps each key to a value Order does not matter Given a key, can look up a value – Given a value, cannot look up its key No duplicate keys – Two or more keys may map to the same value Keys and values are Python values – Keys must be immutable (not a list, set, or dict) Can add key → value mappings to a dictionary – Can also remove (less common) 5 → 25 7 → 49 6 → → “Revolutionary” 1848 → “Mexican” 1865 → “Civil” “Revolutionary” → “Mexican” → “Civil” → → 25 7 → 49 6 → 36 “Revolutionary” → “Mexican” → “Civil” → “WWI” → add mapping 7 → → → 7 49 → -7 2

Dictionary syntax in Python d = { } d = dict() us_wars_by_end = { 1783: "Revolutionary", 1848: "Mexican", 1865: "Civil" } us_wars_by_name = { "Civil" : [1861, 1865], "Mexican" : [1846, 1848], "Revolutionary" : [1775, 1783] } Syntax just like lists, for accessing and setting: us_wars_by_end[1783]  us_wars_by_end[1783][1:10]  us_wars_by_name["WWI"] = [1917, 1918] 1783 → “Revolutionary” 1848 → “Mexican” 1865 → “Civil” “Revolutionary” → “Mexican” → “Civil” → Two different ways to create an empty dictionary

Creating a dictionary >>> state_capitals = {"GA" : "Atlanta", "WA": "Olympia" } >>> phonebook = dict() >>> phonebook["Alice"] = " " >>> phonebook["Bob"] = " " >>> atomic_number = {} >>> atomic_number["H"] = 1 >>> atomic_number["Fe"] = 26 >>> atomic_number["Au"] = 79 “GA” → “Atlanta” “WA” → “Olympia” “Alice” → “ ” “Bob” → “ ” “H” → 1 “Fe” → 26 “Au” → 79 4

Accessing a dictionary >>> atomic_number = {"H":1, "Fe":26, "Au":79} >>> atomic_number["Au"] 79 >>> atomic_number["B"] Traceback (most recent call last): File " ", line 1, in atomic_number["B"] KeyError: 'B' >>> atomic_number.has_key("B") False >>> atomic_number.keys() ['H', 'Au', 'Fe'] >>> atomic_number.values() [1, 79, 26] >>> atomic_number.items() [('H', 1), ('Au', 79), ('Fe', 26)] Good for iteration (for loops) for key in mymap.keys(): val = mymap[key] … use key and val for key in mymap: val = mymap[key] … use key and val for (key,val) in mymap.items(): … use key and val “H” → 1 “Fe” → 26 “Au” → 79 5

Iterating through a dictionary atomic_number = {"H":1, "Fe":26, "Au":79} # Print out all the keys: for element_name in atomic_number.keys(): print element_name # Another way to print out all the keys: for element_name in atomic_number: print element_name # Print out the keys and the values for (element_name, element_number) in atomic_number.items(): print "name:",element_name, "number:",element_number 6

Modifying a dictionary us_wars1 = { "Revolutionary" : [1775, 1783], "Mexican" : [1846, 1848], "Civil" : [1861, 1865] } us_wars1["WWI"] = [1917, 1918] # add mapping del us_wars_by_name["Mexican"] # remove mapping “Revolutionary” → “Mexican” → “Civil” → “Revolutionary” → “Mexican” → “Civil” → “WWI” → add mapping 7

Dictionary Exercises What does this do? squares = { 1:1, 2:4, 3:9, 4:16 } squares[3] + squares[3] squares[3 + 3] squares[2] + squares[2] squares[2 + 2] Convert a list to a dictionary: Given [5, 6, 7], produce {5:25, 6:36, 7:49} Reverse key with value in a dictionary: – Given {5:25, 6:36, 7:49}, produce {25:5, 36:6, 49:7} 8

Dictionary Exercise (Answers) Convert a list to a dictionary: – E.g. Given [5, 6, 7], produce {5:25, 6:36, 7:49} d = {} for i in [5, 6, 7]:# or range(5, 8) d[i] = i * i Reverse key with value in a dictionary: – E.g. Given {5:25, 6:36, 7:49}, produce {25:5, 36:6, 49:7} k ={} for i in d.keys(): k[d[i]] = i 9

A list is like a dictionary A list maps an integer to a value – The integers must be a continuous range 0..i mylist = ['a', 'b', 'c'] mylist[1]  'b' mylist[3] = 'c' # error! In what ways is a list more convenient than a dictionary? In what ways is a list less convenient than a dictionary? 10

Not every value is allowed to be a key in a dictionary Keys must be immutable values – int, float, bool, string, tuple of immutable types – not: list, set, dictionary The dictionary itself is mutable (e.g. we can add and remove elements) Goal: only dictionary operations change the keyset – after “ mydict[x] = y ”, mydict[x]  y – if a == b, then mydict[a] == mydict[b] These conditions should hold until mydict is changed Mutable keys can violate these goals 11

Not every value is allowed to be a key Keys must be immutable values – int, float, bool, string, tuple – not: list, set, dictionary Goal: only dictionary operations change the keyset – after “ mydict[x] = y ”, mydict[x]  y – if a == b, then mydict[a] == mydict[b] These conditions should hold until mydict itself is changed Mutable keys can violate these goals list1 = ["a", "b"] list2 = list1 list3 = ["a", "b"] mydict = {} mydict[list1] = "z"  Hypothetical; actually illegal in Python mydict[list3]  "z" list2.append("c") mydict[list1]  ??? mydict[list3]  ??? 12