Chapter 8 Dictionaries. Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values.

Similar documents
Dictionaries. By- Neha Tyagi PGT CS KV 5 Jaipur II Shift Jaipur Region. Based on CBSE Curriculum Class -11. Neha Tyagi, KV 5 Jaipur II Shift

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

COMP1730/COMP6730 Programming for Scientists. Dictionaries and sets

Data Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value.

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections

Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH

MEIN 50010: Python Data Structures

LECTURE 3 Python Basics Part 2

Chapter 14 Tuples, Sets, and Dictionaries. Copyright 2012 by Pearson Education, Inc. All Rights Reserved.

Data Structures. Lists, Tuples, Sets, Dictionaries

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Collections. Lists, Tuples, Sets, Dictionaries

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Introduction to Bioinformatics

6. Data Types and Dynamic Typing (Cont.)

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

Variable and Data Type 2

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

More Data Structures. What is a Dictionary? Dictionaries. Python Dictionary. Key Value Pairs 10/21/2010

More Examples Using Lists Tuples and Dictionaries in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #11

Dictionaries. Upsorn Praphamontripong. CS 1111 Introduction to Programming Spring 2018

Chapter 8 SETS AND DICTIONARIES

Python. Olmo S. Zavala R. Python Data Structures. Lists Tuples Dictionaries. Center of Atmospheric Sciences, UNAM. August 24, 2016

Basic Python Revision Notes With help from Nitish Mittal

Overview.

Python Lists 2 CS 8: Introduction to Computer Science Lecture #9

COLLEGE OF ENGINEERING, NASHIK-4

Python Programming: Lecture 2 Data Types

Python - Variable Types. John R. Woodward

The Practice of Computing Using PYTHON

Sequences and iteration in Python

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries

Advanced Algorithms and Computational Models (module A)

Lecture 21. Chapter 12 More Python Containers

Lecture #12: Mutable Data. map rlist Illustrated (III) map rlist Illustrated. Using Mutability For Construction: map rlist Revisited

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I

TREES AND MUTATION 5

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

COMP 204: Dictionaries Recap & Sets

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

Python Evaluation Rules

ENGR (Socolofsky) Week 07 Python scripts

CIS192 Python Programming

Python Intro GIS Week 1. Jake K. Carr

Lecture #12: Mutable Data. Last modified: Sun Feb 19 17:15: CS61A: Lecture #12 1

Chapter 2: Lists, Arrays and Dictionaries

A list can also be empty: empty_list = [] Lists are similar to strings, but there are a few key differences.

Announcements COMP 141. Lab from Last Time. Dictionaries 11/29/2017. CS1: Programming Fundamentals

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Here n is a variable name. The value of that variable is 176.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Python. Karin Lagesen.

Functions, Scope & Arguments. HORT Lecture 12 Instructor: Kranthi Varala

Compound Data Types 2

DSC 201: Data Analysis & Visualization

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

COMP10001 Foundations of Computing Functions

Lists, Tuples and Dictionaries. HORT Lecture 10 Instructor: Kranthi Varala

CSE 115. Introduction to Computer Science I

Notebook. March 30, 2019

CSC Software I: Utilities and Internals. Programming in Python

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

Introduction to Python

DSC 201: Data Analysis & Visualization

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Here is a simple dictionary in Python. Let s store the telephone dialing codes for a few countries.

Rapid Application Development with

An introduction to Python

PYTHON DATA SCIENCE TOOLBOX II. List comprehensions

Java+- Language Reference Manual

CS 234 Python Review Part 2

TUPLES AND RECURSIVE LISTS 5

University of Texas at Arlington, TX, USA

Data Structure in Python for Data Analytics Prof. Zhang CISC5835, Fall Basic Built-in Python Data Structures

Introduction to Python! Lecture 2

CSC326 Python Sequences i. CSC326 Python Sequences

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Introduction to Python

Python Basics. 1 of 7 9/5/2018, 8:51 AM. txt1 = "ada lovelace, english mathematician and writer" print(txt1)

Introduction to Python

WELCOME CSCA20 REVIEW SEMINAR

APCS Semester #1 Final Exam Practice Problems

Swift. Introducing swift. Thomas Woodfin

Python and Bioinformatics. Pierre Parutto

Python I. Some material adapted from Upenn cmpe391 slides and other sources

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

VENTURE. Section 1. Lexical Elements. 1.1 Identifiers. 1.2 Keywords. 1.3 Literals

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python


Teaching London Computing

University of Washington CSE 140 Introduction to Data Programming Winter Midterm exam. February 6, 2013

Unit 2. Srinidhi H Asst Professor

Python. Executive Summary

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CS111 Jeopardy: The Home Version

Data Science Python. Anaconda. Python 3.x. Includes ALL major Python data science packages. Sci-kit learn. Pandas.

Lecture 7: Python s Built-in. in Types and Basic Statements

Transcription:

Chapter 8 Dictionaries Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values. Creating a Dictionary To create a dictionary, you need to include the key:value pairs in curly braces as per following syntax: <dictionary-name> = {<key>:<value>, <key>:<value>.. } Following is an example dictionary by the name teachers that stores the names of teachers as keys and the subjects being taught by them as values of respective keys. teachers= { Dimple : Computer Science, Karen : Sociology, Harpreet : Mathematics, Sabah : LegalStudies } Following table illustrates the key-value relationships in above dictionary teachers. Some more examples of dictionary declarations: One thing that you must know is that keys of a dictionary must be of immutable types, such as : o A Python string o A number o A tuple If you try to give a mutable type as key, Python will give you an error as : unhashable type. See example below: Accessing Elements of a Dictionary In dictionaries, the elements are accessed through the keys defined in the key:value pairs, as per the syntax shown below: <dictionary-name> [key] P a g e 1 14

The keys act like indexes to access values from a dictionary. Also, attempting to access a key that doesn t exist causes an error. Consider the following statement that is trying to access a non-existent key (13) from dictionary d. Traversing a Dictionary It means accessing and processing each element in it. The for loop makes it easy to traverse or loop over the items in a dictionary, as per following syntax: for <item> in <Dictionary> : process each item here The loop variable <item> will be assigned the keys of <Dictionary> one by one, which can be used inside the body of the for loop. d1 = {5 : number, a : string, (1,2) : tuple } To traverse the above dictionary, we can write for loop as : for key in d1: print(key, :, d1[key]) How Traversing works The loop variable key win above loop will be assigned the keys of the dictionary d1, one at a time. P a g e 2 14

Loop variable key will be assigned 5 in first iteration and hence the key 5 and its value number will be printed ; in second iteration, key will get element a and its value string will be printed along with it. ** Dictionaries are unordered set of elements, the printed order of elements is not same as the order you store the elements in it. Accessing Keys or Values Simultaneously - To see all the keys of a dictionary in one go, you may write <dictionary>.keys( ) and to see all values in one go, you may write <dictionary>.values( ). d = { Vowels : a, Vowel2 : e, Vowel3 : i, Vowel4 : o, Vowel5 : u } >>> d. keys( ) dict_keys([ Vowel5, Vowel4, Vowel3, Vowel2, Vowel1, ]) >>> d. values( ) dict_values([ u, o, i, e, a ]) Characteristics of a Dictionary 1. Unordered Set A dictionary is a unordered set of key:value pairs. Its value can contain references to any type of object. 2. Not a Sequence Unlike a string, list and tuple, a dictionary is not a sequence because it is unordered set of elements. The sequences are indexed by a range of ordinal numbers. Hence, they are ordered, but a dictionary is an unordered collection. 3. Indexed by keys, Not numbers Dictionaries are indexed by keys. According to Python, a key can be any non-mutable type. P a g e 3 14

4. Keys must be unique Each of the keys within a dictionary must be unique. Since keys are used to identify values in a dictionary, there cannot be duplicate keys in a dictionary. However, two unique keys can have same values, 5. Mutable Like Lists, dictionaries are also mutable. We can change the value of a certain key in place using the assignment statement as per syntax: <dictionary> [<key>] = <value> Multiple ways of creating Dictionary 1. Initializing a Dictionary In this method all the key:value pairs of a dictionary are written collectively, separated by commas and enclosed in curly braces. Employee = { name : John, salary : 10000, age : 24} P a g e 4 14

2. Adding key:value Pairs to an Empty Dictionary To create an empty dictionary, there are two ways: (i) By giving dictionary contents in empty curly braces as shown below: Employees = { } (ii) By using dictionary constructor dict( ) as shown below: Employee = dict( ) Next Step is to add key:value pairs, one at a time as per syntax given below: <dictionary>[key] = <value> Employee[ name ]= John Employee[ salary ]= 10000 Employee[ age ] = 24 3. Creating a Dictionary from name and value pairs (I) Specific Key : Value pairs as keyword argument to dict( ) function (II) Specify comma separated key:value pairs (III) Specify keys separately and corresponding values separately In this method, the keys and values are enclosed separately in parentheses and are given as arguments to the zip( ) function, which is then given as argument of dict( ). The zip function clubs first value from first set with the first value of second set, second value from first set with the second value of second set and so on. (IV) Specify Key:Value pairs separately in form of sequences P a g e 5 14

In this method, one list or tuple argument is passed to dict( ). Adding Elements to Dictionary Key being added must not exist in dictionary and must be unique. If the key already exists, then this statement will change the value of existing key and no new entry will be added to dictionary. <dictionary>[<key>] = <value> Updating Existing Elements in a Dictionary You can change value of an existing key using assignment as per following syntax : <dictionary> [<key>] = <value> P a g e 6 14

Deleting Elements from a Dictionary There are two methods for deleting elements from a dictionary. First Method Key:value pair can be deleted using del command as per the following syntax: del<dictionary>[<key>] But with del statement, the key that you are giving to delete must exist in the dictionary, Otherwise Python rises exception(keyerror). Second Method pop( ) method can be used to delete elements from a dictionary as per following syntax: <dictionary>.pop(<key>) The pop( ) method will not only delete the key:value pair for mentioned key but also return the corresponding value. P a g e 7 14

If you try to delete a key which does not exist, the Python returns error. Checking for Existence of a Key - Usual membership operators in and not in work with dictionaries as well. It can be used as: <key> in <dictionary> <key> not in <dictionary> - The in operator will return True if the given key is present in the dictionary, otherwise False. - The not in operator will return True if the given key is not present in the dictionary, otherwise False. - However, if you need to search for a value in a dictionary, then you can use the in operator with <dictionary_name>.values( ), i.e., >>> 24 in empl.values( ) True Pretty Printing a Dictionary - If you have a dictionary as Winners = { Nihar :3, Rohan : 5, Zeba :3, Roshan :1, James :5 } and if you give a print( ) to print it, Python will give result as : >>> print( Winners) { Nihar :3, Rohan : 5, Zeba :3, Roshan :1, James :5 } - But if dictionary consist of many elements then above method will not be presentable or may be readable. In such cases function dumps( ) of json module can be used as per following syntax inside print( ) : P a g e 8 14

Dictionary Functions and Methods 1. The len( ) method 2. The clear( ) method - This method removes all items from the dictionary and the dictionary becomes empty dictionary post this method. The syntax to use this method is given below: <dictionary>.clear( ) - Takes no argument, returns no value - The clear method does not delete the dictionary, it just deletes all elements inside the dictionary. If however, you want to delete the dictionary itself so that dictionary is also removed and no object remains, then you can use del statement along with dictionary name. P a g e 9 14

3. The get( ) method - With this method, you can get the item with the given key as per the following syntax: <dictionary>.get( key) Takes key as argument and returns corresponding value if the key exists or when key does not present, it gives error. 4. The items( ) method - This method returns all of the items in the dictionary as a sequence of (key,value) tuples. <dictionary>.items( ) - Takes no argument; Returns a sequence of (key, value) pairs. Example: 5. The keys( ) method This method returns all of the keys in the dictionary as a sequence of keys (in form of a list). <dictionary>.keys( ) - Takes no argument ; Returns a list sequence of keys. 6. The values( ) method This method returns all the values from the dictionary as a sequence (a list). <dictionary>.values( ) - Takes no argument ; Returns a list sequence of values. P a g e 10 14

7. The update( ) method - This method merges key:value pairs from the new dictionary into the original dictionary, adding or replacing as needed. The items in the new dictionary are added to the old one and override any items already there with the same keys. Practice Questions ************ Q1. How are dictionaries different from lists? Lists are sequential collections(ordered) and dictionaries are non-sequential collections(unordered). Q2. Consider the following code fragments. What outputs will they produce? (i) adict = { Bhavna : 1, Richards : 2, Firoza : 10, Arshnoor : 20 } temp = 0 for value in adict.values( ) : temp = temp + value print(temp) (ii) adict = { Bhavna : 1, Richards : 2, Firoza : 10, Arshnoor : 20 } temp = 0 for key in adict : if temp < key : temp = key print(temp) (iii) adict = { Bhavna : 1, Richards : 2, Firoza : 10, Arshnoor : 20 } k = Bhavna v = -1 if k in adict : adict[k] = v print(adict) Sol2. (i) 33 (ii) Richard (iii) { Bhavna : -1, Richards : 2, Firoza : 10, Arshnoor : 20 } Q3. Write a Python program that takes a value and checks whether the given value is part of given dictionary or not. If it is, it should print the corresponding key otherwise print an error message. P a g e 11 14

Sol3. dict1= {0: Zero, 1: one, 2: Two, 3: Three, 4: Four, 5: Five } val = input( Enter Value: ) for k in dict1 : if dict1[k] == val : print( exist at, k) else : print( Not Found ) Q4. Why is a dictionary termed as an unordered collection of objects? Q5. What type of objects can be used as keys in dictionaries? Q6. In no more than one sentence, explain the following Python error and how it could arise: TypeError : unhashable type : list Q7. Dictionary is a mutable type, which means you can modify it contents? What all is modifiable in a dictionary? Can you modify the keys of a dictionary? Q8. How is del D and del D[<key>] different from one another if D is a dictionary? Q9. How is clear( ) function different from del<dict> statement? Q10. The following code is giving some error. Find out the error and correct it. d1 = { a : 1, 1 : a, [1, a ] : two } Q11. Nesting of dictionary allows you to store a dictionary inside another dictionary. Then why is following code raising error? What can you do to correct it? d1 = { 1 : 10, 2 : 20, 3 : 30 } d2 = { 1 : 40, 2 : 50, 3 : 60 } d3 = { 1 : 70, 2 : 80, 3 : 90 } d4 = { d1 ; a, d2 : b, d3 : c } Q12. Why is following code not giving correct output even when 25 is a member of the dictionary? di = { age : 25, name : xyz, salary : 23450.5 } val = dic1[ age ] if val in dic1 : print( This is member of the dictionary ) else: print( This is not a member of the dictionary ) Q13. What is the output produced by above code: d1 = {5 : [6,7,8], a : (1,2,3)} print(d1.keys( )) print(d1.values( )) Q14. Consider the following code and then answer the questions that follow: mydict = { a : 27, b :43, c :25, d :30 } vala = for i in mydict : if i > vala : vala = i valb = mydict[i] print(vala) #Line1 print(valb) #Line2 print(30 in mydict) #Line3 mylst = (mydict.items( )) mylst.sort( ) #List4 print(mylst[-1]) #List5 (i) (ii) What output does Line1 produce? What output does Line2 produce? P a g e 12 14

(iii) (iv) (v) What output does Line3 produce? What output does Line5 produce? What is the return value from the list sort( ) function (Line5) and what it its type? Q15. What will be the output produced by following code? d1 = { 5 : number, a : string, (1,2) : tuple } print( Dictionary contents ) for x in d1.keys( ) : print(x, :, d1[x], end= ) print( d1[x] * 3) print( ) Q16. Predict the output : (a) fruit = { } L1 = [ Apple, banana, apple ] for index in L1 : if index in fruit : fruit[index] += 1 else: fruit[index] = 1 print(len(fruit)) print(fruit) (b) arr = { } arr[1]=1 arr[ 1] = 2 arr[1] += 1 sum = 0 for k in arr : sum += arr[k] print(sum) Q17. Find the error/output. Consider below given two sets of codes. Which one will produce an error? Also, predict the output produced by the correct code. (a) box = { } jars = { Jam : 4 } crates = { } box[ biscuit ] = 1 box[ cake ] = 3 crates[ box ] = box crates[ jars ] = jars print(len(crates[box])) (b) box = { } jars = { Jam : 4} crates = { } box[ biscuit ] = 1 box[ cake ] = 3 crates[ box ] = box crates[ jars ] = jars P a g e 13 14

print(len(crates[ box ])) Q18. Create a dictionary whose keys are month names and whose values are the number of days in the corresponding months. (a) Ask the user to enter a month name and use the dictionary to tell how many days are in the month. (b) Print out all of the keys in alphabetical order. (c) Print out all of the months with 31 days. Q19. Write a program that checks if two same values in a dictionary have different keys. That is, for dictionary D1={ a :10, b :20, c :10 }, the program should print 2 keys have same values and for dictionary D2={ a :10, b :20, c :30 }, the program should print No keys have same values. *********************** P a g e 14 14