Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
76 views
dictionaries in python
Python dictionary
Uploaded by
goverdhan133648
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save dictionaries in python For Later
Download
Save
Save dictionaries in python For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
76 views
dictionaries in python
Python dictionary
Uploaded by
goverdhan133648
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save dictionaries in python For Later
Carousel Previous
Carousel Next
Save
Save dictionaries in python For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 26
Search
Fullscreen
6.1 INTRODUCTION information. In the previous chapter, we discussed about li but data structures that store related dat eee ita items, Inthis eee we will focus on another important Python collection /sequence, viz. an unordered sequence/collection called Dictionary. Unlike sequences, Python collections do not have any order. They are unordered and unindexed data structures. This means that it is not neceses to get the order in which we insert items. ° fequence) which are nothing ‘Sequences or Collections In @ Python lassification of Sequences/Collections in Python Fig. 6. > What is ordered and unordered collection in Python? Ordered collection/sequence refers to the arrangement of elements in the ane ederas they are specified initially. So strings, iis and tuples are ordered collections of objects. intain this order. tae on ae A collection comprises elements which have their order n the other hen’ ‘nitial order. For example, in sets and dictionaries, initial order—the ea Tee ene’ the elements—is not maintained. So sets and dictionaries are w order in whic ne bjects.* unordered collections of ol cionaries are ordered. In Python 36nd eal versions dclonales were unordered. jetionaries are) “As of Python version 3.7, Scanned with CamScannerelated to a sequence. Sequence oF, say, a collection, with y, ae performed one after the other, q 4," we are alrea st 4 light sequence is the mo: " < oie has several types of sequences such as lists which we have tay ud vet tn Chapter 5. All these sequences share the following r Jic concept r contains several items or operations ‘common example of a sequence which we encounter at most eye urning to the basi Now tu b familiar, already discuss common features: nce conti > Each sequel or of Traffic Light } The elements are arranged in some order in the sequence. Sequence > tis possible to iterate over the elements in the sequence, according to their ord Je to check if an element is in a sequence or not. u ya ‘ains a finite number of elements. > Itis also po: Let us now discuss an unordered sequence, dictionary and related Fig. 6.2:4 Coy functions in detail. sone 6.2 DICTIONARY IN PYTHON You can use collections to create database-like structures using Python. Bach collection type has a different purpose and you use the various types in specific ways, The important thing to remember is that collections are simply another kind of sequence. Here, we are going to discuss a collection in Python which is known as Dictionary. The main purpose of a dictionary is to map unique keys oof with a value so that retrieving information is optimized when we know the key. Za Dictionaries are mutable and we can simply add new key-value pairs in the dictionary by assigning them. A telephone directory can be compared to a dictionary in Python. As in a telephone directory a subscriber's number gets stored according to his name and address. So, name becomes a key for reference and telephone number becomes the value to be searched for. Similarly, in Python too, we have a concept of key-value pair using dictionary. Python dictionary is an ordered collection of items where each item is a key-value pair We can also refer to a dictionary as a mapping betWeen a set of keys/indices and a set of values: {"Python" : "Dictionaries"} Important Features. of Dictionaries: 1, Each key maps to a value. The association of a key and a value is called a key-value pair, 2. Each i fae Ly crated from its value by a colon (:), the items are commas, and th icti any ys entire dictionary is enclosed in Keys are unique with 4 a . “nique within a dictionary while values may not be. valu ea nae See can be of any type, but the keys must be 2 ‘ype such as strings, numbers or tuples. 7 Informatics Practices with Python-xI Scanned with CamScannerVALUES CIM: Dictionaries are mutable, unordered collections wit ey th elements in the form of key-value pairs that creating a Dictionary (Initializing a Dictionary) ‘A dictionary can be created by placing items (ie,, key- ae separated by a comma, (ie, key-value pait) inside curly braces (}, syntax: edictionary_name> = (key1':'value1';key2':'value2’, ‘key3':'value3’..keyn': 'valuen’} ‘A dictionary is extremely useful data storage construct for storing and retrieving all key-value pairs, where each element is accessed (or indexed) by a unique key. Examples of dictionary >>>d=(} # empty dictionary Values >>> dictl= ("R': "Rainy", 'S":"Summex', Winter', 'A':"AUE Keys e076) [HSC V. Python 3.6.5 (v3.6.5:£59c0932b4, Nar 28 2018, 1800 32 bit (Intel)} on win32 type “copyright”, “credits” or “License ()" for more information Se> d= ( ) fempty dictionary S>> dicti= ('R': Rainy", 15" :"sunmer', >>> print (dict) tRainy', ‘8! ‘sunmer', ‘W': 'Winter!, ‘at: ‘Autunn') s'winter", ‘A":"autunn') ‘The keys of a dictionary are of immutable t be changed. Internally, dictionaries red) on the basis of keys. In the second example, ‘R, ‘S, 'W' and ‘W are the keys and ‘Rainy’, ‘Summer’, ‘Winter’ and ‘Autumn’ are the values associated with the keys, >>> Learning Tip: type, /e, they cannot are indexed (le. arrang and values are st q key as integer tthreet,4:!four') # # here both keys and :tone',2:"two! ues are intege: >>> dl=(1:10,2:20,3:30/4:40} ¥ Key-value pairs 1,2,3) #"numbers", 1-5 float") >>> d2=(1: "one", "two": 2, ( >>> a2 ee Scanned with CamScannerta stones "two: 2, (2s 3) :‘numbers) 1.5 : float’) ON fe different data types are used f0 dofine keys of the dictionary like integer, float. Note: Dictionary k distinctly. 6.3 METHODS TO CREATE key-val each key is separated fro Map, B ey are case-sensitive fe, same name but different cases of key yy . bet ety 4 A DICTIONARY 1e pairs are separated by a comma and are enclosed , ‘To create a dictionary, 1m Its value by a colon (:), praces {). In key-value pain, Moca Practical Implementation-1 To create an empty dictionary o> dl = (1 >>> type (dl)
by assigning two curly braces to a variable name: practical Implementation-2 nary using string data type for both key-value pairs. To create a dictio :tprinter', ("input ': "keyboard", ‘output! >>> d2= "python", '0S': 'windows-8'} ‘language': >>> print (42) {‘input': ‘keyboard’, ‘windows-10") ‘output’: ‘printer', ‘language’: ‘python’, Practical Implementation-3 To create a dictionary with built-in function dict(). The functi dictionary with no items. >>> Dedict () >>> print (D) 0 {} represent an empty dictionary. dict() function can also be used to create a ci i ‘opy of dictio i ict argument to dict() function. 4 aA att ion dict() is used to create anew jonary 35 For example, >>> aa(1:1,2:2) >>> bedict (a) >>>b {1: 1, 2: 2) To add an item along with the key. to the dictionary, we can use square brackets[) for initializing diction®") ie Syntax: edictionary_name>[ key] =
ice aka Scanned with CamScannerpractical Implementation-4 \d an item to an empty di Ce ari pty dictionary using square brackets{}. 3 y> DIL] = "ONE" 33> pt2] = "TWO" Sy> DI3] = "THRE! Sp> D[4) = "FOUR" Sop print (D) (a: TONE", 2: "TWO", 32 “THREE, 4: ‘FOUR') Here, 1, 2,3 and 4 are keys corresponding to values “ONE”, "TWO", "THREE", "FOUR" ‘ E’, respectively. 6.4 ACCESSING ELEMENTS IN A DICTIONARY To access dictionary elements, you can use th 7 e famil At Reo SHR ceaae liar square brackets{] along with the key to >>> eictL = {'Name': 'Riya', 'Age': 7, 'Class': 'second'} >>> print ("dict1['Name']: ", dicti('Name']} dict] ['Name']: Riya Nain er Note: To access dictionary elements >>> print ("dictl [Age]: ", dictl ['Age"]) tan use the guare brackets org with the key to obtain its value. dicti['age']: 7 If we attempt to access a data item with a KeyError as follows: >>> dictl = {'Name': 'Riya’ >>> print ("dict1['aman"] Traceback (most recent call last): File "
", line 1, in
print ("dict1 ["Aman']: ", dict1 (‘aman']) key, which is not a part of the dictionary, we get ‘age': 7, 'class': 'second'} , dict] ['Aman"]) keyError: ‘Aman’ 6.5 TRAVERSING A DICTIONARY means accessing each ele! ile loop for iterating bet Traversing a dictionary ment of a dictionary. This can be done by using afor loop or may use a Ww! tween the dictionary elements. in operator using for loop: Traversing a dictionary means | 3:!three',4:'four') [ Note: >>> de{1:"one!,2:'two'y >>> for i ind: Jecessing each element of 2 fort ing ay ee a print (4,'t') 2 1% cetorioop er while 0p. | 1 sng be 2: two 3: three 4: four rates each key of a dictionary. operator in for loop ite Dictionary Scanned with CamScanneree ee Practical Implementation-5 Write a program to enter names of employees and their salaries as input and store ¢ dictionary (using for loop). Here num fs the input by the user. “Covmrrneineronancen trunnion tennant Hie es atin. Wwrite a program to enter nanes of exployens art their salaries as legit Hand steve them ina dictionary (sing for lorp) fhumeint (input (enter the minal of employems! “)) count =} employee = aictt) 1° count in range tum + fare = rp © Int (input Enter the 8 ‘employes inane} salary print (*\n\emmrncvel nent eRART®) FW empleyest Print Oks VEE empleyeeted) dn empty aetsenary the name of the taploee: are MEATAPT: C1 /Ueers/prosts rypoata/ticas, Seloop2.p7 inter the honbar of empaysens 4 Enter the name of thn teghoyees ‘Aiea linvar the salary: 12600, enter the hase of the bepliyen: tajad enter the salary: 67000 Enter the nana of the Baployee: Rajat enter the salary: 90000, enter Phe nase Of the Eepleyen: Yast enter ‘the salary: 43000, 72000 e000 Practical Implementation-6 Write a program to input total number of sections and stream name in 11" class and di information on the output screen. print Anput ("Enter total nusber of sections An xi clas Jeiite seems Anput ("Enter section: *) Deinput ("enter stream nano: *) clacsxs (a) type “copysight*, "eredste” oF "scene Joneccenecenernesneenn RESTART! C1/Chapter 1/prgh_$,py *omeeannuanneneeensnee eater totat muaber of sections tn a class: gee PE inter sections & linver stzean nanet SCIENCE WITH Eco inter Section! Yea Masa! SCIENCE WITH B10 ethont c inter stzean Nanas SCIENCE WITH cB inter Section! inter stream anor COMMERCE WITH KATHE inter Section; )* £0r nore information, stream mans COMMRCE WITH 27 ‘ection ‘Stream nave a Scxeuce WITH C0 SCIENCE wrTH B10 © SCKENCE WITH cs D COMMERCE WITH HATS 2 Conbence WITH TP (VM !ntormatics Practices with Python-X! : hem in , isplay all Scanned with CamScanner6.6 APPENDING VALUES IN j DICTIONARY fe can add new elements to ¢ . es Mieronariee ints one, ree easing detonary, extend it with single pair of values or join ianee 0 add on! i" igmety dia new xey-value pair will be added at the end ofthe dicimany en syntax: me Dictionary name[key]=value Note: We can add new elements to the existing I dictionary, extend it with single pair of Dan values of join two dictionaries into one. por d=("mon': 'monday", ‘tue! + ' t "tuesday!, ‘wedi: © ; >>> di (thu']= ‘thursday? Seay Neds ‘wednesday') >>> print (dl) {'mon': "monday", 'tue': 'tuesday', ‘wed't 'wednesday', 'thu': 'thursday') 6.7 UPDATING ELEMENTS IN A DICTIONARY You can also update a dictionary by modifying existing key-value pair or by merging another dictionary with an existing one. Syntax: if key is there in the dictionary, ji _ then it will update the value of that
[
]=
A particular key in the dictionary. For example, >>> Dict = {'Teena': 18, 'Riya} >>> Dict ['Riya']=28 412, "Alya':22, 'Ravi':25} i i IFkey isnot there in the dictionary, meee ee then it will add key-value pair at {'Teena': 18, 'Riya': 28, 'Alya': 22, 'Ravi': 25} _|the end of the dictionary. >>> Dict ['Priya']=60 / >>> print (Dict) {'"Teena': 18, 'Riya': 28, 'Alya': 22, 'Ravi': 25, ‘Priya’: 60} Note: While adding a value, if the key value already exists, the value gets updated, Otherwise, a new key with the value is added at the end of the dictionary. Two dictionaries can be merged into one by using update() method. It merges the keys and values of one dictionary with another and overwrites values of the same key. Syntax: dict_namet.update(dict_name2) Using this, dict_name2 is added to dict_name1, For example, >>> di 02:20, 3:30) >>> d2=(4:40,5:50) >>> di. update (d2) >>> print (d1) {1: 10, 2: 20, 3: 30, 43 40, 5: 50) >>> print (d2) (4: 40, 5: 50) aE Dictionary @ Scanned with CamScannerFor example, >>> dl={1: 10, 2: 30, 3: 30, 5: 40, 6: 60} >>> d2=(1: 10,2: 20,3: 30) >>> dl.update (a2) Value of key 2 Is replaced {1: 10, 2: 20, 3: 30, 5: 40, 6: 60) >>> print (d2) {1: 10, 2: 20, 3: 30) 6.8 REMOVING AN ITEM FROM DICTIONARY We can remove an item from the existing dictionary by using del command or using pop) method: 1, using del command: Syntax: del dictname[key] For example, >>> A={"mon": "monday", "tue": "tuesday", "wed": "wednesday", "thu": "thursday"} >>> del A['wed"] >>> print(A) {"'mon': 'monday', 'tue' >>> del A['fri'] See Traceback (most recent call last): File "
", line 1, in
del A['fri']” KeyError: 'fri!——— ‘tuesday’, 'thu': 'thursday'} then it will result in KeyEor If you want to delete the entire dictionary, then give the dictionary name along with del keyword without any key. For example, >>>del A >>> Traceback (most recent call last): File "
", line 1, in
A NameError: name 'A' is not defined The dictionary named A no longer exists in the memory. 2, using pop() method: pop() method will not only delete the item specified by the key fro" the dictionary but also return the deleted value, 74 Informatics Practices with Python-X| Scanned with CamScannersyntai dictname.pop(key) For example, >>> D3={ "mon" : "mong, >>> D3.Pop(‘tue') oe : ‘quesday' wednesday") y>> print(b3)_ + | aa eee faa value, {'mon': ‘monday’, + ay", ‘tuer, opitem() method: 3. aa d: It returns and Temoves the last inserted (key, syntax: dictname.popitem() For example, value) pair from the >>> d3=(1: 10, 2: 20, 3: 45 3:45, 5: 40, 6: : eee 6: 60, 8: 50, 4: 40) (4:40) 6.9 MEMBERSHIP OPERATOR: ‘in’ AND ‘not in’ The ‘in’ operator checks whether a Particular key i in the dicti a specified Ney appears i the aitton ey is there in the dictionary. It returns True if ary, otherwise returns False. >>> Ae{"mon": "monday", "tue": "tuesday", "wed" : "wednesday", "thu" :" >>> ‘thu! in A True >>> "frit in a False >>> "fri! not in A True CTM: The membership operator ‘in’and functions like min), max() and sum() apply only to the keys in 2 dictionary. 6.10 COMMON DICTIONARY FUNCTIONS AND METHODS Python provides you with a number of ways to manipulate the dictionary. Let us check out some of the important ones with examples. Python Dictionary Methods nary Scanned with CamScannerdictionary. iven len() irs in the give! ‘This method returns length of key-value P=! Syntax: len(d) # dis dictionary sro in te dictionary returns total number of key-value on 10, 62 60) >>> dl={1: 10, 2: 30, 3: 30, 5 >>> Len (dl) 5 clear() urns an empty dictionary, - dictionary and ret It removes all items from the particular dictio y Synta: dclear() # disdictionary For example, >>> D={1:'one',2:'two', >>> print (D) {1: 'one', 2: 'two', >>> D.clear () >>> print (D) 0 get() method The get() method returns a value for the given key. If key is not available, then returns the default value None. Syntax: Following is the syntax for get() method: dict.get(key, default=None) key: This is the key to be searched in the dictionary. default: This is the value to be returned in case the key does not exist. This method returns a value for the given key. If key is not available, then returns default value None. For example, >>> Dl= 3:'three!,4:'four') ‘three', 4: 'four') *sun':'Sunday', 'mon':'Monday', 'tue': ‘thu! : 'Thursday'} >>> Dl.get ("wed") "Wednesday" >>> print (D1.get ("fri") ) None "Wednesday's "Tuesday", ‘wed will return None as key does not exist You can specify your own message also; >>> Dl.get ('fri', ‘never') "never! ama] Here, we have specified our oe message but ifthe key exists thn will return its value, not customize® >>> Dl.get ('mon’, 'never!) "Monday! MV "cvates Practices with Pytnon-x1 4 Scanned with CamScannerirems() the content of dicti iereturns ictionary as a li " St of tuples having key-value pairs. paitems() # Dis dictionary For example, ppp Datsun" "Sunday", ‘mon: Hondas "tue': "Tuesday", twed! :1 ‘ | urns a Y's "wed": 'Wednesdayt, | Net han ane of tuples | ‘thu! "Thursday! ) >>> D.items() ees” aict_items({("sun', ‘sunday'), (mon', 'Monday'), (‘tue', 'Tuesday'), ('wed", 'Wednesday'), (‘thu', 'Thursday') }) keys() Itreturns a list of keys in a dictionary, Syntax: Dkeys()_ #Disdictionary For example, >>> De{"sun': 'Sunday', 'mon': 'Nonday', 'tue': "Tuesday", ‘wed’ :"Wednesday', ‘thu': "Thursday"} >>> D. keys () dict_keys(['sun', 'mon', 'tue', 'wed', 'thu']) values() It returns a list of values from key-value pairs in a dictionary. Dvalues() #Disdictionary For example, >>> De{ "sun "thu': 'Thursday')} "sunday", 'mon': "Monday", 'tue': "Tuesday", "wed": "We >>> D.values () dict_values({*Sunday', 'Monday', 'Tuesday', 'Wednesday', copy() We cannot copy a dictionary by using assignment (‘=') operator as it will create a reference to the same dictionary variable and modifications done in any of the dictionaries will be reflected in both dictionaries. We can use built-in function copy() to create a new dictionary object by copying it that doesn’t modify the original dictionary. Syntax: Dict_new=Dict_old.copyO. E wa tionary 2 Scanned with CamScannerFor example, >>> dl={"January":31, "February":28 } >>> ded] <——_ >>> dl ning a dict {"January': 31, ‘February’: 28} >>> a2 "3 "131, "February': 28} ae ee Sener! Changes made to d2 are ego >>> d2["March"}=31 indi ced) >>> d2 Z {"January': 31, "February': 28, ‘March’: 31} >>> dl (‘ganuary': 31, "February': 28, 'March': 31) Soh pi aL >>>. d3 {"January': 31, 'February': 28, 'March': 31) [Ghanges made Indi aeron cory flected in d3 | >>> 41 ["April”]=30 = >>> a3 a ({‘January': 31, 'February': 28, 'March': 31 } >>> dl {‘January': 31, 'February': 28, 'March': 31, 'April': 30) Practical Implementation-7 WAP to store students’ information like admission number, roll number, name and matisin; dictionary and display information on the basis of admission number. ‘SCidict () isa flag=0 neint (input ("Enter nunber of entries:")) while i
>> RESTART: Ct /Users/preeti/APp ven-diction.py ‘add New Contact Display all Delete any contact Modify/Change Phone Number check if a friend is present or not Display in sorted order of names Exit Enter your choice 2 Enter name + Tarun Enter phone number Record Added + 9856630383 had New contact Display 81) oe Beiste any conta ge prone Monee Moaify/changs pa is present, of not neck Af 5 ented order of names Exit ‘4 pelete any He moaify/change ead is present oF not a check if orted corde Exit Scanned with CamScanner pata/Local/Programs/Python/Python37-32/prog_menudri,Enter your choice : 2 |[Name Tarun Contact number : 9856636383 Name : Rakesh Contact number : 786888869 Enter your choice : 4 Enter the new nameaditya Record Modified 1. add New Contact 2. Display all 3. Delete any contact * 4, Modify/Change Phone Nunber 5. Check if a friend is present or not 6. Display in sorted order of names 7, Bxit Enter your choice : 2 fwame Tarun [contact nunber : 9856638363 ame: Aditya Jcontact nunber : 786888869 1. Add New Contact 2. Display all 3. Delete any contact 4. Modify/Change Phone Number 5. check if-a friend is present or not 6. Display in sorted order of names 7, Bxit fEnter your choice : 6 laditya /rarun 11. add New Contact 2. Display all 3. Delete any contact 4. Modify/Change Phone Number 5. Check if a friend is present or not 6. Display in sorted order of names 7. Brit Enter your choice + 7 o> Enter the contact number to be modi fied786888869 — ¥, MEMORY BYTES > APython dictionary is a mapping of unique keys to values. It is a collection of key-value pairs. Dictionaries at mutable which means they can be changed, > Ina dictionary each key maps to a value. The association of a key and a value is called a key-value pair. > The keys of a dictionary must be unique and immutable, > To create a dictionary, key-value pairs are separated by a comma and are enclosed in two curly braces (!" key-value pair, each key is separated from Its value by a colon (:) > We can add new elements to the existing dictionary, into one. extend it with single pair of values or join two dictionat®* > The membership operators in and not in only work with dictionary keys > We can also update a dictionary by modifying existing key-value pair or by merging another dictionary wih existing one, > Python provides us with a number of dictionary methods like len(), pop( items(), keys(), values(), getl), et Scanned with CamScannery RN oBsECTIVE TYPE QUESTIONS Lb te ena 1. Fill in the blanks. ae Dictionaries are ... which f aa ieisien ne means they can be changed. (9 The attociton ofa keyana'veckcg era keys to values, It Is a collection of key-value pairs. (d) To create a dictionary, key-value pairs are se a @. news function returns the keys of the alt a (g) Keys of a dictionary must be .., mm {h) To delete an element, you can either use... statement fh zs nt or use (i) The .. sore function returns . total number of key: iti eae ce of key-value pairs in a dictionary. .. method. Pees which is not in a dictionary using _ funetion, 2, State whether the following statements are True or False. (a) An element in a dictionary is a combination of key-value pair, {b) Internally, dictionaries are indexed on the basis of values. (c) We can repeat a key in dictionary. (d) In dictionary, two unique keys can have same values. {e).clear() is used to delete a dictionary. (f) The key of a dictionary is a mutable data type. {g) List can be used as keys in a dictionary. (h) Updation of an element in a dictionary at runtime is possible. (i) We can create immutable dictionaries in Python. 3. Multiple Choice Questions (MCQs): (2) Which of the statement{s) is/are correct? jonary is an ordered collection of items. (ii). Python Dictionary is a mapping of unique Keys to values. (iii) Dictionary is mutable. (iv) All of the above. (b) To create an empty dictionary, we use the statement 2s: ; () dist (i) dt=0) (ii) aa=0) (iv) at==0) i hf (@) Ina dictionary, the elements are accessed throug ) w key one (ii) value (iii) label {iv) None of these {d) Keys of a dictionary must be: ih Unfave Similar . All of th i) Both (i) and (ill tists Here rent Bee seston fem (i) dt=() (iv) Both (i) and (i) (i) Dict (0) Which funetion i used co atu ae forthe “st) (iv) None of these i) ji) ge (e) Rea ieen js used to remove all items froma peat srvenar pe eletel i) ch (h) a vite the output of the following Python code snippet? 40, "jatin"s45) 466, "jatin":45) i) Error {iv) None ji) False \ i) Te y veil returns keyvale palts ofthe delonary inthe form of Ist of tuples? (Which ofthe following funn ast (i) iters() (iv) eet) (i) key() Dictionary QB Scanned with CamScanneree i) Select the correct option to get the values of marks Key. | Student~("name": "Emma", “class":11, "sec": "a", “ma (i) Student.get(3) (i)' Student.get(“marks”) (iii) Student{*marks"] {iv) both (ii) and (ii) SOLVED QUESTIONS =e 1. What is a dictionary? ‘Ans. APython dictionary is a mapping of unique keys to values. Its a collection of key-value pairs, Dictionay fare mutable which means values can be changed. es tored in dictionaries different? re be of any data type (even the type NONE) but keys can n 2. How are objects st ‘Ans. The objects or values stored in a dictionary can immutable type-objects, €.g., strings, Integers, etc. 3. Write a code to create an empty dictionary. Ans. >>> dl= {1} OR >>> dl = dict () >>> print (dl) 44, Can sequence operations such as slicing and concatenation be applied to dictionaries? Why/Why not? {Hots \g and concatenation cannot be applied to dictionaries 2s dictionary ‘Ans. No, sequence operations such as slicing ‘intained in any specific order or we may say arranged in the order is not a sequence, Since they are not ms of insertion, operations that depend on a specific order cannot be used. 5. Why can’t lists be used as keys? (Hors) ‘Ans. Lists cannot be used as keys in a dictionary because they are mutable and a Python dictionary can have oniy keys of immutable types. 6. If the addition of a new key-value pair causes the size of the dictionary to grow beyond its original size, it shall result in an error. True or false? [HOTS] ‘Ans. False. No error shall occur because dictionaries are mutable in nature and they can grow or shrink as ané when required. 7. What are the differences between lists and dictionaries? ‘Ans. In list, elements are enclosed within square brackets whereas in dictionary key-value pairs are enclosed within curly braces. In dictionary, index value can be of any data type (except list) and is called key, but in list, index value is an integer. 8. Find errors, underline them and rewrite the same after correcting the following code: dl =dict{] i-l n= input ("Enter number of entries:") while i<=n: a= input ("Enter name b = input ("Enter age:") di(a) =b i=itl l=di.key[) foriinl: print(i,'\t','dl[i]') Ans, dl = dict ( i=l n= int (input ("Enter number of entries:")) while i a = input ("Enter name b= input ("Enter age difa]=b i=itl Informatics Practices with Python-X! Scanned with CamScanner1 = dl.keys() foriinl: print (i,"\t",diti 9, Consider the followin, suatecapstal = (nse nay Statecepial rajasthan": "Jaipur") Find the output of the following statements: (b) print (stateCapital. keys ()) , (c) print (stateCapital values ()) (a) print (stateCapital.items()} (e) print (Len (stateCapital)) (f) print ("Maharashtra” in stateCapital) (g) print (stateCapital.get ("Assam") ) (h) del stateCapital ("Assam") print (stateCapital) Ans. (a) Patna’ Guwahati", “Aihar":"Patna", "Maharashtra": "Mumbai", ” (b) dict_keys(['Assam', 'Bihar', ‘Maharashtra’, 'Rajasthan']) (¢) dict_values({ "Guwahati", ‘Patna’, 'Mumbai', 'Jaipur']) {d) dict_items({('Assam', 'Guwahati'), ("Bihar', ‘Patna'), (‘Maharash "Mumbai'), ("Rajasthan', 'Jaipur')]) fe) 4 () True (e) ‘Guwahati (h) { "Bihar": "Patna", "Maharashtra": "Mumbai", "Rajasthan": "Jaipy 10. Consider the dictionary ‘mon’ given below and do as directed: mon = {"Jan':31, 'Feb':28, 'Mar':31, 'April':30) {a) Find the incorrect statement(s) out of the following: (i) print (mon['Jan"} ii) print (mon(28]) {b) Write the output of the following code: mon ("Feb"] = 29 print (mon) del mon{"April"] print (mon) mon.clear() print (mon) ‘Ans. (a) Both the statements are incorrect. The correct statements are: (i) print (mon["Jan']) #elosing bracket is missing ")* print (mon['Feb']) #Element can be accessed using Keys (b) (*gan': 31, 'Feb's 29, 'Mar': 31, ‘april’: 30) {'gan': 31, 'Feb': 29, 'Mar's 31) oO 11, Write the output of the following codes: (a) di=(1:10, 2120, 3:30, 4140/5350) print (di. items ()) print (di.keys ()) print (di.values ()) (b) a1=(1:10, 2:20, 3130/4540) d2={5:50, 6160/7170) dl.update (d2) print (42) Bitame 0 nary Scanned with CamScanner160,7:70) (c) di=(1:10, 2:20, 3:30, 4:40, 5250, 6:60 del d1[3] print (dl) (d) dl=(1:10,2:20,3:31 dl.pop (5) print (dl) (e) di=(1:10,2:20,3:30, len(dl) di.get (6) d1[6)=65 dl[s print (dl) dil.clear() ee 4, 40), (8, $0)1) ‘Ans. (a) dict_items({(1, 10), (2, 20), (3, 30)+ ( Gict_keys({1, 2, 3, 4, 5]) dict_values([10, 20, 30, 40, ey 61.60, 11 70) 0, 4:40, 5250, 6260/7270) 4240,5150, 6:60/7:70) 0, 4: 40, ° io, 5: 50, 6: 60, 7: 70) (a) (1: 10, 2: 20, 3: 30, 4: 40, 6: 60, 7: 70) (e) 7 60 {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 65, 7: 70, 8: 35) 1) 32, Write a Python program to find the 2 ma wm values in a dictionary D with key-value pairs zg {1A':23, 'B':56, 'C':29,.'D':42, 'E':78} The output should be displayedas: ‘Two maximum values are 78 56 Ans. D={'A' : 23, 'BY: 56, 'C!: 29, 'D' : 42, "Et : 78) val=[] v= D.values () for iin val .append (i) val.sort () print ("Two maximum values are") print (val[-1]), print (val [-2]) 13. Write a Python program to input ‘n’ names and phone Aumbers to store it in a dictionary and print the phone number of a particular name. Ans. phone=dict () ie n=int (input ("Enter number of entries:")) while ic=n ‘nput ("Enter Name:") ‘put ("Enter Phone no:") Phone[a]=b i=it+. 1 = phone. keys () "input ("Enter name to be searched fori ini: if inex: Print (x,"z phone no is:", phone[i]) break else; Print(x, "does not exist") Informatics Practices with Python-x) _ d Scanned with CamScanneroutput: Enter number of entries: 4 Enter Name:Riya Enter Phone no:9999 Enter Name:Aman Enter Phone no:1111 gnter Name:Pulkit Enter Phone no:5555 gnter Name: Ziya Enter Phone no:2222 Enter name to be searched: Aman aman : phone no is: 1111 44, Write a Python program to create a Dictionary wi - nar et thoracter: The sample DUT ith key as first character and value as wards starting with Enter string: python is 4 pe: [tpython") s interpreted language i: [‘is', interpreted") 1: [‘language"] Ans, test_string=input ("Enter string est_string. split () a0 for word in 1: if (word[0] not in d.keys())+ d{word(0]]=(1 d[word[0]] «append (word) else: if (word not in d{word[0]])+ d{word(0}] append (word) for k,v in d.items(): print (k,":"/v) 15, Write a Python program to input names of ‘n’ employees and their salary detalls like Basic salary, Nose rent and conveyance allowance. Calculate total salary of each employee and display it Ans. d=dict () iel neint (input ("Enter number of entrie: while i< hm-input ("\nEnter name of the employee: ") basic=int (input ("Enter Basic salary: ")) hrasint (input ("Enter house rent allowanc cavine (input ("Enter conveyance allowance: ")) di (Nm) ={basic,hra, ca] ieitl 1 = di.keys() print ("\nNlame”, "\t\e', "Wet Salary") for i in 1: salary = 0 z= d1{i) for j in z: salary=salaryt) print (i, '\t\e',salary) Dictionary SB Scanned with CamScanner ”) Note: list is stored in dictionary as value.Output: Enter number of entries:4 Enter name of the employee: Nishant Enter Basic salary: 100000 Enter house rent allowance: 30000 Enter conveyance allowance: 5000 Enter name of the employee: Ram Enter Basic salary: 50000 Enter house rent allowance: 15000 Enter conveyance allowance: 5000 Enter name of the employee: Aushim Enter Basic salary: 200000 Enter house rent allowance: 50000 Enter conveyance allowance: 10000 Enter name of the employee: Riya Enter Basic salary: 25000 Enter house rent allowance: 2000 Enter conveyance allowance: 1000 Name Net Salary Nishant 135000 Ram 70000 Aushim 260000 Riya 28000 mes fn countries and their capital and currency, storetina dictionary . wate aython programtoinput na papelintle sai hand display for a particular country. and display in tabular form. Also searct Ans. di=dict () inl neint (input ("Enter number of entries while i<-n: c-input ("Enter Country: cap=input ("Enter Capital:") nput ("Enter currency of country:") (cap, curr] # Holding the country details as a list isin 1 = dl.keys() print ("\nCountry\t\t", "Capital \t\t", "Curzency") for 4 inl: zed1 [i] print (‘\n',i,'\t\t',end="") for jin z: print (j,"\t\t!,end="\t\t") x=input ("\nEnter Country to be searched: for 4 in 1: if teex: print ( zedi(i] print ("\n',i,"\t\t!,end= for j in 2: print (3, '\t\t!,end="\t\t") Output: Enter number of entries:5 Enter Country:Austria Enter Capital :Vienna Enter currency of country:Euro rh Informatics Practices with Python-XI ) # searching ncountry\t\t", "Capital\t\t", "Currency\t\t") ) Scanned with CamScannergnter Country:China Enter Capital:Beijing Enter currency of co) gnter CountryIndia Y?%u8" Enter Capital:New Delhi Enter currency of cou ntry: ee oe country: Indian Rupee enter aris gnter currency of count: ryt Ener Country:United Kingdom Enter Capital:London Enter currency of country: Pound country Capital 7 curr austria Vienna tire china Beijing Yuan India New Delhi i 0 France Paris he united Kingdom London Pound Enter Country to be searched: India country capital currency India New Delhi Indian Rupee 17, Write a program to find the number of occurrences of each letter cha i acter pr ri wie oe present in the string inputted Ans. word = input ("Enter any word: ") a-0) for i in word: d[i] = d.get (1,0) +1 for k,v in d.items()? print (k, "occurred", v, "times") Output: Enter any word: nitinhello n occurred 2 times i occurred 2 times t occurred 1 times h occurred 1 times e occurred 1 times 1 occurred 2 times 0 occurred 1 times the number of occurrences of each vowel present in the input ted string. 418, Write 2 program to find Ans, word = input ("Enter the string + ” vowels = ("a's d={} for i in word? if i in vowels? ati] = d-get (4/0 k,v in sorted (d, items ())¥ voecurred” vr "eimes") ter, Ht tore ad ped for print (Ky Output: Enter the string? pythonprogramming a occurred 1 times 4 occurred 1 times 9 occurred 2 times Dictionary a Scanned with CamScanner19, Write a function to convert a number entered by the user Into Its corresponding num 2 iber For example, i the input is 985, then the output should be ‘Nine Elght Five’. un "i Ans. #Program to convert number into corresponding number in words fnunberNames is a dictionary of digits and corresponding number numberNames = {0:'Zero', 1 yA: Four’, \ S:'Pive',6:'Six', eight", 91 'Nine'} num = input ("Enter any number: ") Hnumber Le stored as string result =" for ch in num: key = int (ch) #converts character into integer value = nunberNanes [key] result = result +" ' + value print ("The number is:", num) print ("The numberName i result) UNSOLVED QUES TONS $$ 11, What is a key-value pair in dictionary? 2. What are the differences between strings and dictionary? 3. Find errors and rewrite the same after correcting the following code: (a) di=(1:10, 2.5220, 3:30, 4:40, 5:50, 6:60, 7:70} (b) a1(9)=90 (©) dei ai (2) (@) pop ai (4) (e) di.item() (f) dt.key() (@) at.value() th) di.gets (4,80) x! (i) dt-ten() @) di.ctears() 4. Suppose >>> dl=(1:'one',2:'two',3:'three!, 4: four! } >>> d2=(5:' five’, 6:'six'} Write the output of the following code: (a) >>> dt.items() Me >>> dl.keys() >>> dl.values() >>> dl update (d2) >>> Len (dl) (b) >>> del 41(3} >>> print(di) >>> dl.pop (4) >>> print (dl) >>> di [8]="eight! >>> print (dl) >>> dl.clear() >>> print (di) 5, WrlteaPithon program tind the 2 maximum values ina detlonay, 5. Wrte a Python program to input‘ n' classes and names of thelr ei ‘tina dictionary! display the same. Also, accept lass teachers to store it ina dictions aiieeeas ‘Pt @ particular class from the user and display the name of the class te _Informatics Practices with Python-x1 Scanned with CamScanners their Also gh Percentage in a dictior Nh _ tiation he etry ayaa nary, delete a particular student number, store it in a diction; 9, what type of objects can be used as keys in dt lonaries? ). How will 40, How will you check fora value inside a dletionary ud 411, How is clear!) function different from del() ae mail 42, The following code is giving some error. Find o ‘i ne - Find out Uy "amy e"twom) 413, What will be the output of the following code? di = (5: (67/81, "a": (1,2,3)} print (dl.keys()) print (dl. values ()) 14, Predict the output: (a) d= ((2,2) 2, (2,3) 22) print (d[1,2]) (b) d= (ats, "b':2, '0":3} print (d{'a', "b']) the error and write the corrected cade. 415, Write a program to input your friends’ dette keyvalue po. Perorm te folowing operations ontiediionsye (a) Display the Name and Phone numbers of all your friends. {b) Adda new key-value pair in this dictionary and display the modified dictionary. (c) Delete a particular friend from the dictionary. (4) Modify the phone number of an existing friend. {e) Check ifa friend is present in the dictionary or not. (f) Display the dictionary in sorted order of names, 16. Consider the following dictionary Prod_Price. 'yeD': 25000, 'Laptop': 35000, ‘Home Theatre’: 80000, Prod Price = { "18000, ‘Electric Iron": 2800, "Speaker "Microwave Oven Find the output of the following statements: (a) print (Prod_Price-get ("Laptop") (b) print (Prod_Price.keys()) (c) print (Prod_Price.values()) (a) print (Prod_Price. items ()) {e) print (len (Prod_Price)) (f) print ('Speaker' in Prod_Price) (g) print (Prod Price.get ("UCD") (h) del Prod_Price{'Home Theatre'] int (Prod_Price) pts the user for product names and prices and store these key-value pairs in Pe the keys and prices are the values, Also, write 2 code to search product in 17. write a program that prom price. If the product Is not there In the dictionary, then display the relevant a dictionary where names a a dictionary and display Its whether the inputted valve is part of the given message. : a value and checks and print the corresponding key, otherwise print an ‘error message. Dictionary Scanned with CamScannery sED/SOURCE-BASED INTEGRATED QUESTIONS eee CASE-BA’ lise including groceries, fruits, vege » vegetal «adepartment store with a wide range of merchand 4, Pure Basket Jop a complete software for Billing, Inventory and Acco les ssories, taims to develop OUNtS mang hy noel aes ga sere ete ow Rm codes an sf varositeny, My an : repeatedly asks the user to enter product names and prices, s v" program in Python that Write a prog fare product names and values are prices. Also write a code tg yr¢ ate them in a dictionary whose Keys item from the dictionary. f Ans. mii. = |\fhrcaran to store the details of qiocories and their prices coy! atte rch ety! or chest Y's paseetnput(santer the product nana *) ‘Sepeysetar tanpue (veneer the product peice 1°) ettome) price keeleertdoe you want to add nove Atoms (1/4") posneeatce) nmerinpat ("enter the product to be eearched # Poin atets Tel Sptod names odbet found” Ay ult piles tet) RESTART: C:/Users/preat /Appoata /Local /Prograns/Python/| Jental_store_dictl.py Jexter"tne product name:Sugar Eater the product price 160 bo you vant to aad moro items (Y/MY Do you vant £0 add more itens (x/)n Tisuger': 60). "Elscuits: 30, ‘Detergent Powder": 300) ister the product to be ireaits Product fobnd Biscuits with price ast 20 2. With respect to transaction details of customers stored in the “Bank” (Ch-5), the phone numbers ofthe customers are to be stored in the form of a dictionary. Write a Python program to input names and phone numbers of the customers and store them in a dictionary. Also, search name of any customer in the dictionary and display his/her phone number. an. ‘Beutonerpy-CirenriezrpdaalecremaniPyroyPesblewoneroyG8 —— OX eeu format an Opis ow Hee Re reo eet SRE came! ox chee astameeinpe runeer the customer nape") owtinpueCzacer the customer neblie mabe: ‘Sict{eustnane)=phone ‘Cheinput ("Do you want to add more custoner details (¥/1)") peine aie est anedapct"ncernane ot the cotonr tobe arched or") nydict iD) pions Window Help " eHeEETER, Oct 20RD, TETSUTAO) (HSE Wana &4 BIE (MH eedite” of *1icense()" for nore information, fm’nesrants c:/Users/veee2/spppeta/Local/Prograns/ython/ Pyenona?/custenes PY fencer the custonor nanet Rita linter the custoner mobile nnber:087678879 bo you went to ead more eystoner dataile (Y/10Y linear she customer nena: dal. enter the custaner nobile nanber:679@97878 Do you vane to ada pore gustonsr details (1/1n (Cateas sbe7e70079", "a5ey" figs: 979897078") fencer nane of the cuitoner co be searched £0r/A30Y [ustener Ainy “has nobite manera #7099989 Informatics Practices with Python-XI Scanned with CamScanner
You might also like
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
From Everand
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life
Mark Manson
4/5 (6387)
Principles: Life and Work
From Everand
Principles: Life and Work
Ray Dalio
4/5 (634)
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
From Everand
The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are
Brené Brown
4/5 (1160)
Never Split the Difference: Negotiating As If Your Life Depended On It
From Everand
Never Split the Difference: Negotiating As If Your Life Depended On It
Chris Voss
4.5/5 (983)
The Glass Castle: A Memoir
From Everand
The Glass Castle: A Memoir
Jeannette Walls
4/5 (8302)
Grit: The Power of Passion and Perseverance
From Everand
Grit: The Power of Passion and Perseverance
Angela Duckworth
4/5 (633)
Sing, Unburied, Sing: A Novel
From Everand
Sing, Unburied, Sing: A Novel
Jesmyn Ward
4/5 (1254)
The Perks of Being a Wallflower
From Everand
The Perks of Being a Wallflower
Stephen Chbosky
4/5 (10337)
Shoe Dog: A Memoir by the Creator of Nike
From Everand
Shoe Dog: A Memoir by the Creator of Nike
Phil Knight
4.5/5 (933)
Her Body and Other Parties: Stories
From Everand
Her Body and Other Parties: Stories
Carmen Maria Machado
4/5 (887)
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
From Everand
The Hard Thing About Hard Things: Building a Business When There Are No Easy Answers
Ben Horowitz
4.5/5 (361)
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
From Everand
Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race
Margot Lee Shetterly
4/5 (1007)
Steve Jobs
From Everand
Steve Jobs
Walter Isaacson
4/5 (3237)
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
From Everand
Elon Musk: Tesla, SpaceX, and the Quest for a Fantastic Future
Ashlee Vance
4.5/5 (581)
The Emperor of All Maladies: A Biography of Cancer
From Everand
The Emperor of All Maladies: A Biography of Cancer
Siddhartha Mukherjee
4.5/5 (297)
A Man Called Ove: A Novel
From Everand
A Man Called Ove: A Novel
Fredrik Backman
4.5/5 (5058)
Angela's Ashes: A Memoir
From Everand
Angela's Ashes: A Memoir
Frank McCourt
4.5/5 (943)
The Art of Racing in the Rain: A Novel
From Everand
The Art of Racing in the Rain: A Novel
Garth Stein
4/5 (4346)
The Little Book of Hygge: Danish Secrets to Happy Living
From Everand
The Little Book of Hygge: Danish Secrets to Happy Living
Meik Wiking
3.5/5 (458)
The Yellow House: A Memoir (2019 National Book Award Winner)
From Everand
The Yellow House: A Memoir (2019 National Book Award Winner)
Sarah M. Broom
4/5 (100)
Brooklyn: A Novel
From Everand
Brooklyn: A Novel
Colm Toibin
3.5/5 (2091)
Yes Please
From Everand
Yes Please
Amy Poehler
4/5 (1993)
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
From Everand
Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America
Gilbert King
4.5/5 (278)
The World Is Flat 3.0: A Brief History of the Twenty-first Century
From Everand
The World Is Flat 3.0: A Brief History of the Twenty-first Century
Thomas L. Friedman
3.5/5 (2283)
Bad Feminist: Essays
From Everand
Bad Feminist: Essays
Roxane Gay
4/5 (1077)
The Woman in Cabin 10
From Everand
The Woman in Cabin 10
Ruth Ware
3.5/5 (2780)
A Tree Grows in Brooklyn
From Everand
A Tree Grows in Brooklyn
Betty Smith
4.5/5 (2032)
The Outsider: A Novel
From Everand
The Outsider: A Novel
Stephen King
4/5 (2838)
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
From Everand
The Sympathizer: A Novel (Pulitzer Prize for Fiction)
Viet Thanh Nguyen
4.5/5 (141)
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
From Everand
A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story
Dave Eggers
3.5/5 (692)
Team of Rivals: The Political Genius of Abraham Lincoln
From Everand
Team of Rivals: The Political Genius of Abraham Lincoln
Doris Kearns Goodwin
4.5/5 (1912)
Wolf Hall: A Novel
From Everand
Wolf Hall: A Novel
Hilary Mantel
4/5 (4086)
On Fire: The (Burning) Case for a Green New Deal
From Everand
On Fire: The (Burning) Case for a Green New Deal
Naomi Klein
4/5 (76)
Fear: Trump in the White House
From Everand
Fear: Trump in the White House
Bob Woodward
3.5/5 (830)
Manhattan Beach: A Novel
From Everand
Manhattan Beach: A Novel
Jennifer Egan
3.5/5 (906)
Rise of ISIS: A Threat We Can't Ignore
From Everand
Rise of ISIS: A Threat We Can't Ignore
Jay Sekulow
3.5/5 (143)
John Adams
From Everand
John Adams
David McCullough
4.5/5 (2544)
The Light Between Oceans: A Novel
From Everand
The Light Between Oceans: A Novel
M L Stedman
4.5/5 (813)
The Unwinding: An Inner History of the New America
From Everand
The Unwinding: An Inner History of the New America
George Packer
4/5 (45)
Little Women
From Everand
Little Women
Louisa May Alcott
4.5/5 (2369)
The Constant Gardener: A Novel
From Everand
The Constant Gardener: A Novel
John le Carré
4/5 (277)