CSC 231 - Introduction to Data Structures Devon M. Simmonds Computer Science Department University of North Carolina Wilmington Wilmington, NC 28403

Slides:



Advertisements
Similar presentations
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Advertisements

Dictionaries: Keeping track of pairs
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
12. Python - Dictionary A dictionary is mutable and is another container type that can store any number of Python objects, including other container types.
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.
INLS 560 – D ICTIONARIES Instructor: Jason Carter.
CIT 590 Intro to Programming Lecture 7. Agenda Configuring IDLE (now that your code is getting huge) Exceptions Testing for exceptions – the weird self.assertRaises.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L16 (Chapter 22) Java Collections.
1 Sequences A sequence is a list of elements Lists and tuples – Lists mutable – Tuples immutable Sequence elements can be indexed with subscripts – First.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 6: Lists, Tuples, and Dictionaries – Exercises Xiang Lian The University of Texas – Pan American Edinburg,
COMPUTER SCIENCE FEBRUARY 2011 Lists in Python. Introduction to Lists Lists (aka arrays): an ordered set of elements  A compound data type, like strings.
Python Crash Course Containers 3 rd year Bachelors V1.0 dd Hour 3.
Python Crash Course Containers Bachelors V1.0 dd Hour 6.
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.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 14 Tuples, Sets, and Dictionaries 1.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Built-in Data Structures in Python An Introduction.
Computing Science 1P Lecture 14: Friday 2 nd February Simon Gay Department of Computing Science University of Glasgow 2006/07.
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.
CIT 590 Intro to Programming Lecture 6 (dictionaries)
Chapter 9 Dictionaries and Sets.
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.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 10 Lists 1.
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.
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.
Python Programing: An Introduction to Computer Science
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 21 Sets and Maps.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 3: Built-in functions.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
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.
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.
Dictionaries Alexandra Stefan CSE1310 – University of Texas at Arlington.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
Copyright © 2013 by John Wiley & Sons. All rights reserved. SETS AND DICTIONARIES CHAPTER Slides by James Tam Department of Computer Science, University.
Python Fundamentals: Complex Data Structures Eric Shook Department of Geography Kent State University.
11 March 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems
CSc 110, Autumn 2016 Lecture 26: Sets and Dictionaries
10 - Python Dictionary John R. Woodward.
CSc 110, Spring 2017 Lecture 29: Sets and Dictionaries
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
When to use Tuples instead of Lists
Containers and Lists CIS 40 – Introduction to Programming in Python
Department of Computer Science,
Lecture 10 Data Collections
CSc 110, Spring 2018 Lecture 32: Sets and Dictionaries
CSc 110, Autumn 2017 Lecture 30: Sets and Dictionaries
LING 388: Computers and Language
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
Guide to Programming with Python
6. Lists Let's Learn Python and Pygame
Intro to Programming Lecture 5
Introduction to Dictionaries
Dictionaries Dictionary: object that stores a collection of data
6. Dictionaries and sets Rocky K. C. Chang 18 October 2018
Dictionaries: Keeping track of pairs
Introduction to Dictionaries
Dictionary.
Tuple.
Presentation transcript:

CSC Introduction to Data Structures Devon M. Simmonds Computer Science Department University of North Carolina Wilmington Wilmington, NC _____________________________________________________________ Dictionaries..

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 2 Objectives F To store key/value pairs in a dictionary and access value using the key. F To use dictionaries to develop applications.

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 3 Dictionary Why dictionary? Suppose your program stores a million students and frequently searches for a student using the social security number. An efficient data structure for this task is the dictionary. A dictionary is a collection that stores the elements along with the keys. The keys are like an indexer.

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 4 Key/value pairs

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 5 Creating a Dictionary dictionary = {} # Create an empty dictionary dictionary = {"john":40, "peter":45} # Create a dictionary >>> a = dict(one=1, two=2, three=3) >>> b = {'one': 1, 'two': 2, 'three': 3} >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) >>> e = dict({'three': 3, 'one': 1, 'two': 2}) >>> a == b == c == d == e True

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 6 Adding/Modifying Entries To add an entry to a dictionary, use dictionary[key] = value For example, dictionary["susan"] = 50

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 7 Deleting Entries To delete an entry from a dictionary, use del dictionary[key] For example, del dictionary["susan"]

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 8 Looping Entries for key in dictionary: print(key + ":" + str(dictionary[key]))

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 9 The len and in operators len(dictionary) returns the number of the elements in the dictionary. >>> dictionary = {"john":40, "peter":45} >>> "john" in dictionary True >>> "johnson" in dictionary False

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 10 The Dictionary Methods

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Other Built-in Dictionary Functions & Methods: 11 1.cmp(dict1, dict2) - Compares elements of both dict. 2.len(dict) - Gives the total length of the dictionary. 3.str(dict) - Produces a printable string representation of a dictionary 4.type(variable) - Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type. 5.dict.copy() - Returns a shallow copy of dictionary dict 6.dict.fromkeys() - Create a new dictionary with keys from seq and values set to value. 7.dict.has_key(key) - Returns true if key in dictionary dict, false otherwise 8.dict.setdefault(key, default=None) - Similar to get(), but will set dict[key]=default if key is not already in dict 9.dict.update(dict2) - Adds dictionary dict2's key-values pairs to dict

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 12 Built-in Dictionary Functions & Methods: 1.dict.setdefault(key, default=None) - Similar to get(), but will set dict[key]=default if key is not already in dict 2.dict.update(dict2) - Adds dictionary dict2's key-values pairs to dict Previous Page 5.Print Version 6.PDF Version 7.Next Page Advertisements 11.

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 13 Built-in Dictionary Functions & Methods: Python includes the following dictionary functions: SN Function with Description 1 cmp(dict1, dict2) Compares elements of both dict. 2 len(dict) Gives the total length of the dictionary. This would be equal to the number of items in the dictionary. 3 str(dict) Produces a printable string representation of a dictionary 4 type(variable) Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type. Python includes following dictionary methods SN Methods with Description 1 dict.clear() Removes all elements of dictionary dict 2 dict.copy() Returns a shallow copy of dictionary dict 3 dict.fromkeys() Create a new dictionary with keys from seq and values set to value. 4 dict.get(key, default=None) For key key, returns value or default if key not in dictionary 5 dict.has_key(key) Returns true if key in dictionary dict, false otherwise 6 dict.items() Returns a list of dict's (key, value) tuple pairs 7 dict.keys() Returns list of dictionary dict's keys 8 dict.setdefault(key, default=None) Similar to get(), but will set dict[key]=default if key is not already in dict 9 dict.update(dict2) Adds dictionary dict2's key-values pairs to dict 10 dict.values() Returns list of dictionary dict's values Previous Page Print Version PDF Version Next Page Advertisements

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Dictionaries 14 dict = {} for i in range(ord('A'), ord('Z')+1): dict[i-65]= chr(i) for i in range(len(dict)): print(dict[i])

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Dictionary – Sample Code 15 import random myDict = {} MAX = 1000 def makeRandomDict(): dict = {} for i in range(26): key = random.randrange(1, MAX) dict[key]= chr(i+65) return dict def makeDict(dict): for i in range(26): dict[i]= chr(i+65) def printDict(dict): keyList = list(dict) for i in keyList: print(dict[i]) def searchDict(searchKey, dict): keyList = list(dict) print(keyList) if(searchKey in keyList): idx = keyList.index(searchKey) print("FOUND key: ", searchKey, "Value: ", dict[searchKey]) def main(): print(myDict) makeDict(myDict) printDict(myDict) searchDict(7, myDict) dic = makeRandomDict() printDict(dic) searchDict(628, dic) main()

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 16 Case Studies: Occurrences of Words This case study writes a program that counts the occurrences of words in a text file and displays the words and their occurrences in alphabetical order of words. The program uses a dictionary to store an entry consisting of a word and its count. For each word, check whether it is already a key in the dictionary. If not, add to the dictionary an entry with the word as the key and value 1. Otherwise, increase the value for the word (key) by 1 in the dictionary.

© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. The End 17 ______________________ Devon M. Simmonds Computer Science Department University of North Carolina Wilmington _____________________________________________________________ Qu es ti ons?