SlideShare a Scribd company logo
1 of 21
Dictionaries
MAPPING
CONTENT
Characteristic: key-value pair, un ordered, unique pairs(keys),mutable, keys-immutable type
Methods of creating a dictionary:
{ : }
dict(): dict(k1=v1,k2=v2), dict( ((k1,v1) , (k2,v2)) ) dict({k1:v1}), dict(zip( (k1,k2),(v1,v2) ) ), dict.fromkeys(keys,
single value)
Traversing : in, items( )
Adding/updating elements: D[key]=value, setdefault ,update
Deleting elements: del, pop, popitem, clear
Pretty printing –json.dumps()
Dictionary methods: get, keys, values, copy
A Story of Two Collections..
List, tuple, string
A linear collection of values that stay in order
Dictionary
A “bag” of values, each with its own label
Dictionaries
Dictionaries are Python’s most powerful data collection
Dictionaries allow us to do fast database-like operations in Python
Dictionaries have different names in different languages
◦ Associative Arrays - Perl / Php
◦ Properties or Map or HashMap - Java
◦ Property Bag - C# / .Net
http://en.wikipedia.org/wiki/Associative_array
purse = dict()
purse['money'] = 12
purse['candy'] = 3
purse['tissues'] = 75
print(purse)
names = {}
names['B/101'] = "Anusha"
names['B/102'] = "Athish"
print(names)
{'money': 12, 'candy': 3, 'tissues': 75}
{'B/101': 'Anusha', 'B/102': 'Athish'}
Creating a
dictionary
{ : }
DICT(): DICT(K1=V1,K2=V2), DICT( ((K1,V1) , (K2,V2)) )
DICT({K1:V1}), DICT(ZIP( (K1,K2),(V1,V2) ) ), DICT.FROMKEYS(KEYS,
SINGLE VALUE)
List versus Dictionary
Lists index their entries based on the position in the list
Dictionaries are like bags - no order
So we index the things we put in the dictionary with a “lookup tag”
>>> lst = list()
>>> lst.append(21)
>>> lst.append(183)
>>> print(lst)
>>> lst[0] = 23
>>> print (lst)
>>> ddd = dict()
>>> ddd['age'] = 21
>>> ddd['course'] = 182
>>> print(ddd)
>>> ddd['age'] = 23
>>> print(ddd)
Dictionary Tracebacks
It is an error to reference a key which is not in the dictionary
We can use the in operator to see if a key is in the dictionary
>>> ccc = dict()
>>> print ccc[‘January']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>KeyError: ‘January'
>>> print (‘January' in ccc)
False
When we encounter a new name, we need to add a new entry in the dictionary and if this
the second or later time we have seen the name, we simply add one to the count in the
dictionary under that name
counts = dict()
names = ['Amrita', 'Ayush', 'Shriyans','Ayush', 'Rithvik']
for i in names :
if i not in counts:
counts[i] = 1
else :
counts[i] = counts[i] + 1
print(counts)
Two Iteration Variables!
We loop through the key-value pairs in a
dictionary using *two* iteration variables
During each iteration, the first variable is
the key and the second variable is the
corresponding value for the key
>>> j = { ‘Feb' : 1 , ‘Apr' : 42, 'jan': 100}
>>> for a,b in j.items() :
... print (a, b)
...
Feb 1
Apr 42
jan 100
>>>
WAP to create a dictionary company to store company
details like its name and its URL. The company’s
name is treated as key and URL as value. Display all
the company’s names and its URL
Adding/updating elements:
D[key]=value
d={'jan':31}
d['feb']=28
d
{'jan': 31, 'feb': 28}
setdefault
d.setdefault('mar',31)
31
d
{'jan': 31, 'feb': 28, 'mar': 31}
d.setdefault('jan',30)
31
d
{'jan': 31, 'feb': 28, 'mar': 31}
d.setdefault('extra')
d
{'jan': 31, 'feb': 28, 'mar': 31, 'extra':
None}
update
d1={'apr':30,'may':31}
d.update(d1)
d
{'jan': 31, 'feb': 28, 'mar': 31, 'extra': None, 'apr': 30, 'may':
31}
Deleting elements
del
d
{'jan': 31, 'feb': 28, 'mar': 31,
'extra': None, 'apr': 30, 'may':
31}
del d['extra']
d
{'jan': 31, 'feb': 28, 'mar': 31,
'apr': 30, 'may': 31}
pop, popitem, clear
d.pop('may')
31
d
{'jan': 31, 'feb': 28, 'mar': 31, 'apr': 30}
d.popitem()
('apr', 30)
d
{'jan': 31, 'feb': 28, 'mar': 31}
d.clear()
d
{}
Pretty printing –json.dumps()
d
{'jan': 31, 'feb': 28, 'mar': 31}
import json
print(json.dumps(d,indent=2))
{
"jan": 31,
"feb": 28,
"mar": 31
}
JSON: JavaScript Object Notation is a format for
structuring data. It is mainly used for storing and
transferring data between the browser and the server.
Python too supports JSON with a built-in package called
json. This package provides all the necessary tools for
working with JSON Objects including parsing, serializing,
deserializing, and many more.
Dictionary methods:
get keys, values copy
d
{'jan': 31, 'feb': 28, 'mar':
31}
d.get('apr',"not found")
'not found'
d.get('jan')
31
list(d.keys())
['jan', 'feb', 'mar']
list(d.values())
[31, 28, 31]
d1=d
id(d)
1825985322112
id(d1)
1825985322112
d1=d.copy()
id(d1)
1825985315904
sorted, reversed
D1
{'Apr': 30, 'Jun': 30, 'Sep': 30}
sorted(D1)
['Apr', 'Jun', 'Sep']
sorted(D1,reverse=True)
['Sep', 'Jun', 'Apr']
Retrieving lists of Keys and Values
>>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100}
>>> print list(jjj)
['jan', 'chuck', 'fred']
>>> print jjj.keys()
['jan', 'chuck', 'fred']
>>> print jjj.values()
[100, 1, 42]
>>> print jjj.items()
[('jan', 100), ('chuck', 1), ('fred', 42)]
Important points about Dictionaries:
◦ Collection of key – value pairs
◦ Use the key not the index
◦ Key order is not guaranteed.
◦ Attempting to access a key that doesn’t exist causes error.
◦ Dictionaries are mutable. But give a non-mutable type as key (strings,integers,a tuple of
numbers or strings)
◦ But value can be of any type
◦ Unique keys , but values for any unique keys can be same.
◦ Storing a dictionary inside another dictionary
◦ Ex: emp = {‘Swati’ : {‘age’ : 24,’job’: ‘S/E’}, ‘Riya’ : {‘age’ : 22,’job’: ‘Acc’}
◦ You can add elements, update elements, delete elements.
◦ You can clear a dictionary.
1.What’s wrong with the following code?
S = { [2,3,4] : “Numbers”}
2.What’s the output?
Optional = { ‘Rahul’ : ‘Computers’,’Shreyas’ : ‘Economics’}
print(“Optional subject: Rahul: ”, Optional[‘Rahul’])
3. What’s the output?
Optional = { 'Tahul' : 'Computers','Shreyas' : 'Economics'}
a = list(Optional.keys())
print(a)
print(tuple(Optional.values()))
4. Can 2 keys of a dictionary be same? Can the values of 2 unique
keys be same?
5.Will this be an error?
Optional = dict(Name = "Sahil", Subject = 'Economics')
print(Optional)
What is the output?
1) Optional = dict(Name = "Sahil", Subject = 'Economics')
print(Optional)
2) Optional = dict({Name : “Sahil", Subject : 'Economics‘})
print(Optional)
3) Optional = dict(zip( ('Name','Subject'),("Sahil", 'Economics') ) )
print(Optional)
4) Optional = dict( [ [ 'Name','John‘ ] , [ "Subject", 'Economics'] ] )
print(Optional)
5) Optional = dict((('Name','John'),("Subject", 'Economics')))
print(Optional)

More Related Content

Similar to Dictionaries.pptx

Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
Raghu nath
 

Similar to Dictionaries.pptx (20)

Python chapter 2
Python chapter 2Python chapter 2
Python chapter 2
 
Dictionary in python
Dictionary in pythonDictionary in python
Dictionary in python
 
Pytho dictionaries
Pytho dictionaries Pytho dictionaries
Pytho dictionaries
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
 
Dictionary
DictionaryDictionary
Dictionary
 
2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
 
sonam Kumari python.ppt
sonam Kumari python.pptsonam Kumari python.ppt
sonam Kumari python.ppt
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdf
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Python : Dictionaries
 
Python Session - 3
Python Session - 3Python Session - 3
Python Session - 3
 
Module 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptxModule 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptx
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
 

Recently uploaded

VIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
All Types👩Of Sex Call Girls In Mohali 9053900678 Romance Service Mohali Call ...
All Types👩Of Sex Call Girls In Mohali 9053900678 Romance Service Mohali Call ...All Types👩Of Sex Call Girls In Mohali 9053900678 Romance Service Mohali Call ...
All Types👩Of Sex Call Girls In Mohali 9053900678 Romance Service Mohali Call ...
Chandigarh Call girls 9053900678 Call girls in Chandigarh
 

Recently uploaded (20)

VIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Vapi 7001035870 Whatsapp Number, 24/07 Booking
 
Call Girls Katraj Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Katraj Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Katraj Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Katraj Call Me 7737669865 Budget Friendly No Advance Booking
 
VIP Model Call Girls Alandi ( Pune ) Call ON 8005736733 Starting From 5K to 2...
VIP Model Call Girls Alandi ( Pune ) Call ON 8005736733 Starting From 5K to 2...VIP Model Call Girls Alandi ( Pune ) Call ON 8005736733 Starting From 5K to 2...
VIP Model Call Girls Alandi ( Pune ) Call ON 8005736733 Starting From 5K to 2...
 
JM road ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
JM road ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...JM road ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
JM road ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
VVIP Pune Call Girls Narayangaon WhatSapp Number 8005736733 With Elite Staff ...
VVIP Pune Call Girls Narayangaon WhatSapp Number 8005736733 With Elite Staff ...VVIP Pune Call Girls Narayangaon WhatSapp Number 8005736733 With Elite Staff ...
VVIP Pune Call Girls Narayangaon WhatSapp Number 8005736733 With Elite Staff ...
 
VVIP Pune Call Girls Sinhagad Road WhatSapp Number 8005736733 With Elite Staf...
VVIP Pune Call Girls Sinhagad Road WhatSapp Number 8005736733 With Elite Staf...VVIP Pune Call Girls Sinhagad Road WhatSapp Number 8005736733 With Elite Staf...
VVIP Pune Call Girls Sinhagad Road WhatSapp Number 8005736733 With Elite Staf...
 
Baner Pashan Link Road [ Escorts in Pune ₹7.5k Pick Up & Drop With Cash Payme...
Baner Pashan Link Road [ Escorts in Pune ₹7.5k Pick Up & Drop With Cash Payme...Baner Pashan Link Road [ Escorts in Pune ₹7.5k Pick Up & Drop With Cash Payme...
Baner Pashan Link Road [ Escorts in Pune ₹7.5k Pick Up & Drop With Cash Payme...
 
(ISHITA) Call Girls Service Malegaon Call Now 8250077686 Malegaon Escorts 24x7
(ISHITA) Call Girls Service Malegaon Call Now 8250077686 Malegaon Escorts 24x7(ISHITA) Call Girls Service Malegaon Call Now 8250077686 Malegaon Escorts 24x7
(ISHITA) Call Girls Service Malegaon Call Now 8250077686 Malegaon Escorts 24x7
 
VIP Model Call Girls Wadgaon Sheri ( Pune ) Call ON 8005736733 Starting From ...
VIP Model Call Girls Wadgaon Sheri ( Pune ) Call ON 8005736733 Starting From ...VIP Model Call Girls Wadgaon Sheri ( Pune ) Call ON 8005736733 Starting From ...
VIP Model Call Girls Wadgaon Sheri ( Pune ) Call ON 8005736733 Starting From ...
 
VIP Model Call Girls Handewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Handewadi ( Pune ) Call ON 8005736733 Starting From 5K t...VIP Model Call Girls Handewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Handewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
 
Independent Call Girls Pune | ₹,9500 Pay Cash 8005736733 Free Home Delivery E...
Independent Call Girls Pune | ₹,9500 Pay Cash 8005736733 Free Home Delivery E...Independent Call Girls Pune | ₹,9500 Pay Cash 8005736733 Free Home Delivery E...
Independent Call Girls Pune | ₹,9500 Pay Cash 8005736733 Free Home Delivery E...
 
Hinjewadi ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready Fo...
Hinjewadi ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready Fo...Hinjewadi ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready Fo...
Hinjewadi ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready Fo...
 
Daund ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For Se...
Daund ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For Se...Daund ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For Se...
Daund ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For Se...
 
Hadapsar ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For...
Hadapsar ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For...Hadapsar ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For...
Hadapsar ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For...
 
Budhwar Peth { Russian Call Girls Pune (Adult Only) 8005736733 Escort Servic...
Budhwar Peth { Russian Call Girls Pune  (Adult Only) 8005736733 Escort Servic...Budhwar Peth { Russian Call Girls Pune  (Adult Only) 8005736733 Escort Servic...
Budhwar Peth { Russian Call Girls Pune (Adult Only) 8005736733 Escort Servic...
 
Call Girls Junnar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Junnar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Junnar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Junnar Call Me 7737669865 Budget Friendly No Advance Booking
 
Top Rated Pune Call Girls Dehu road ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
Top Rated  Pune Call Girls Dehu road ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...Top Rated  Pune Call Girls Dehu road ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
Top Rated Pune Call Girls Dehu road ⟟ 6297143586 ⟟ Call Me For Genuine Sex S...
 
All Types👩Of Sex Call Girls In Mohali 9053900678 Romance Service Mohali Call ...
All Types👩Of Sex Call Girls In Mohali 9053900678 Romance Service Mohali Call ...All Types👩Of Sex Call Girls In Mohali 9053900678 Romance Service Mohali Call ...
All Types👩Of Sex Call Girls In Mohali 9053900678 Romance Service Mohali Call ...
 
kala ilam specialist expert In UK, london, England, Dubai, Kuwait, Germnay, I...
kala ilam specialist expert In UK, london, England, Dubai, Kuwait, Germnay, I...kala ilam specialist expert In UK, london, England, Dubai, Kuwait, Germnay, I...
kala ilam specialist expert In UK, london, England, Dubai, Kuwait, Germnay, I...
 
Booking open Available Pune Call Girls Sanaswadi 6297143586 Call Hot Indian ...
Booking open Available Pune Call Girls Sanaswadi  6297143586 Call Hot Indian ...Booking open Available Pune Call Girls Sanaswadi  6297143586 Call Hot Indian ...
Booking open Available Pune Call Girls Sanaswadi 6297143586 Call Hot Indian ...
 

Dictionaries.pptx

  • 2. CONTENT Characteristic: key-value pair, un ordered, unique pairs(keys),mutable, keys-immutable type Methods of creating a dictionary: { : } dict(): dict(k1=v1,k2=v2), dict( ((k1,v1) , (k2,v2)) ) dict({k1:v1}), dict(zip( (k1,k2),(v1,v2) ) ), dict.fromkeys(keys, single value) Traversing : in, items( ) Adding/updating elements: D[key]=value, setdefault ,update Deleting elements: del, pop, popitem, clear Pretty printing –json.dumps() Dictionary methods: get, keys, values, copy
  • 3. A Story of Two Collections.. List, tuple, string A linear collection of values that stay in order Dictionary A “bag” of values, each with its own label
  • 4. Dictionaries Dictionaries are Python’s most powerful data collection Dictionaries allow us to do fast database-like operations in Python Dictionaries have different names in different languages ◦ Associative Arrays - Perl / Php ◦ Properties or Map or HashMap - Java ◦ Property Bag - C# / .Net http://en.wikipedia.org/wiki/Associative_array
  • 5. purse = dict() purse['money'] = 12 purse['candy'] = 3 purse['tissues'] = 75 print(purse) names = {} names['B/101'] = "Anusha" names['B/102'] = "Athish" print(names) {'money': 12, 'candy': 3, 'tissues': 75} {'B/101': 'Anusha', 'B/102': 'Athish'}
  • 6. Creating a dictionary { : } DICT(): DICT(K1=V1,K2=V2), DICT( ((K1,V1) , (K2,V2)) ) DICT({K1:V1}), DICT(ZIP( (K1,K2),(V1,V2) ) ), DICT.FROMKEYS(KEYS, SINGLE VALUE)
  • 7. List versus Dictionary Lists index their entries based on the position in the list Dictionaries are like bags - no order So we index the things we put in the dictionary with a “lookup tag” >>> lst = list() >>> lst.append(21) >>> lst.append(183) >>> print(lst) >>> lst[0] = 23 >>> print (lst) >>> ddd = dict() >>> ddd['age'] = 21 >>> ddd['course'] = 182 >>> print(ddd) >>> ddd['age'] = 23 >>> print(ddd)
  • 8. Dictionary Tracebacks It is an error to reference a key which is not in the dictionary We can use the in operator to see if a key is in the dictionary >>> ccc = dict() >>> print ccc[‘January'] Traceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: ‘January' >>> print (‘January' in ccc) False
  • 9. When we encounter a new name, we need to add a new entry in the dictionary and if this the second or later time we have seen the name, we simply add one to the count in the dictionary under that name counts = dict() names = ['Amrita', 'Ayush', 'Shriyans','Ayush', 'Rithvik'] for i in names : if i not in counts: counts[i] = 1 else : counts[i] = counts[i] + 1 print(counts)
  • 10. Two Iteration Variables! We loop through the key-value pairs in a dictionary using *two* iteration variables During each iteration, the first variable is the key and the second variable is the corresponding value for the key >>> j = { ‘Feb' : 1 , ‘Apr' : 42, 'jan': 100} >>> for a,b in j.items() : ... print (a, b) ... Feb 1 Apr 42 jan 100 >>>
  • 11. WAP to create a dictionary company to store company details like its name and its URL. The company’s name is treated as key and URL as value. Display all the company’s names and its URL
  • 12. Adding/updating elements: D[key]=value d={'jan':31} d['feb']=28 d {'jan': 31, 'feb': 28} setdefault d.setdefault('mar',31) 31 d {'jan': 31, 'feb': 28, 'mar': 31} d.setdefault('jan',30) 31 d {'jan': 31, 'feb': 28, 'mar': 31} d.setdefault('extra') d {'jan': 31, 'feb': 28, 'mar': 31, 'extra': None} update d1={'apr':30,'may':31} d.update(d1) d {'jan': 31, 'feb': 28, 'mar': 31, 'extra': None, 'apr': 30, 'may': 31}
  • 13. Deleting elements del d {'jan': 31, 'feb': 28, 'mar': 31, 'extra': None, 'apr': 30, 'may': 31} del d['extra'] d {'jan': 31, 'feb': 28, 'mar': 31, 'apr': 30, 'may': 31} pop, popitem, clear d.pop('may') 31 d {'jan': 31, 'feb': 28, 'mar': 31, 'apr': 30} d.popitem() ('apr', 30) d {'jan': 31, 'feb': 28, 'mar': 31} d.clear() d {}
  • 14. Pretty printing –json.dumps() d {'jan': 31, 'feb': 28, 'mar': 31} import json print(json.dumps(d,indent=2)) { "jan": 31, "feb": 28, "mar": 31 } JSON: JavaScript Object Notation is a format for structuring data. It is mainly used for storing and transferring data between the browser and the server. Python too supports JSON with a built-in package called json. This package provides all the necessary tools for working with JSON Objects including parsing, serializing, deserializing, and many more.
  • 15. Dictionary methods: get keys, values copy d {'jan': 31, 'feb': 28, 'mar': 31} d.get('apr',"not found") 'not found' d.get('jan') 31 list(d.keys()) ['jan', 'feb', 'mar'] list(d.values()) [31, 28, 31] d1=d id(d) 1825985322112 id(d1) 1825985322112 d1=d.copy() id(d1) 1825985315904
  • 16. sorted, reversed D1 {'Apr': 30, 'Jun': 30, 'Sep': 30} sorted(D1) ['Apr', 'Jun', 'Sep'] sorted(D1,reverse=True) ['Sep', 'Jun', 'Apr']
  • 17. Retrieving lists of Keys and Values >>> jjj = { 'chuck' : 1 , 'fred' : 42, 'jan': 100} >>> print list(jjj) ['jan', 'chuck', 'fred'] >>> print jjj.keys() ['jan', 'chuck', 'fred'] >>> print jjj.values() [100, 1, 42] >>> print jjj.items() [('jan', 100), ('chuck', 1), ('fred', 42)]
  • 18. Important points about Dictionaries: ◦ Collection of key – value pairs ◦ Use the key not the index ◦ Key order is not guaranteed. ◦ Attempting to access a key that doesn’t exist causes error. ◦ Dictionaries are mutable. But give a non-mutable type as key (strings,integers,a tuple of numbers or strings) ◦ But value can be of any type ◦ Unique keys , but values for any unique keys can be same. ◦ Storing a dictionary inside another dictionary ◦ Ex: emp = {‘Swati’ : {‘age’ : 24,’job’: ‘S/E’}, ‘Riya’ : {‘age’ : 22,’job’: ‘Acc’} ◦ You can add elements, update elements, delete elements. ◦ You can clear a dictionary.
  • 19. 1.What’s wrong with the following code? S = { [2,3,4] : “Numbers”} 2.What’s the output? Optional = { ‘Rahul’ : ‘Computers’,’Shreyas’ : ‘Economics’} print(“Optional subject: Rahul: ”, Optional[‘Rahul’]) 3. What’s the output? Optional = { 'Tahul' : 'Computers','Shreyas' : 'Economics'} a = list(Optional.keys()) print(a) print(tuple(Optional.values()))
  • 20. 4. Can 2 keys of a dictionary be same? Can the values of 2 unique keys be same? 5.Will this be an error? Optional = dict(Name = "Sahil", Subject = 'Economics') print(Optional)
  • 21. What is the output? 1) Optional = dict(Name = "Sahil", Subject = 'Economics') print(Optional) 2) Optional = dict({Name : “Sahil", Subject : 'Economics‘}) print(Optional) 3) Optional = dict(zip( ('Name','Subject'),("Sahil", 'Economics') ) ) print(Optional) 4) Optional = dict( [ [ 'Name','John‘ ] , [ "Subject", 'Economics'] ] ) print(Optional) 5) Optional = dict((('Name','John'),("Subject", 'Economics'))) print(Optional)