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 2Raghu nath
 
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 notesGOKULKANNANMMECLECTC
 
2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppttocidfh
 
sonam Kumari python.ppt
sonam Kumari python.pptsonam Kumari python.ppt
sonam Kumari python.pptssuserd64918
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfomprakashmeena48
 
Python cheatsheat.pdf
Python cheatsheat.pdfPython cheatsheat.pdf
Python cheatsheat.pdfHimoZZZ
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfsagar414433
 
‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptx‏‏chap6 list tuples.pptx
‏‏chap6 list tuples.pptxRamiHarrathi1
 
Python data structures
Python data structuresPython data structures
Python data structureskalyanibedekar
 
Module 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptxModule 2 - Lists, Tuples, Files.pptx
Module 2 - Lists, Tuples, Files.pptxGaneshRaghu4
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionarySoba Arjun
 
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 WayUtkarsh Sengar
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptxNawalKishore38
 

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

LESSON 1 PREPARE AND COOKING MEAT GRADE 10
LESSON 1 PREPARE AND COOKING MEAT GRADE 10LESSON 1 PREPARE AND COOKING MEAT GRADE 10
LESSON 1 PREPARE AND COOKING MEAT GRADE 10manwithoutapfp
 
PRESTAIR MANUFACTURER OF DISPLAY COUNTER
PRESTAIR MANUFACTURER OF DISPLAY COUNTERPRESTAIR MANUFACTURER OF DISPLAY COUNTER
PRESTAIR MANUFACTURER OF DISPLAY COUNTERPRESTAIR SYSTEMS LLP
 
如何办理新加坡管理大学毕业证成绩单留信学历认证
如何办理新加坡管理大学毕业证成绩单留信学历认证如何办理新加坡管理大学毕业证成绩单留信学历认证
如何办理新加坡管理大学毕业证成绩单留信学历认证zg99vwgda
 
NO1 Top Online Amil Baba in Rawalpindi Contact Number Amil in Rawalpindi Kala...
NO1 Top Online Amil Baba in Rawalpindi Contact Number Amil in Rawalpindi Kala...NO1 Top Online Amil Baba in Rawalpindi Contact Number Amil in Rawalpindi Kala...
NO1 Top Online Amil Baba in Rawalpindi Contact Number Amil in Rawalpindi Kala...Amil baba
 
Abortion pills in Jeddah +966572737505 <> buy cytotec <> unwanted kit Saudi A...
Abortion pills in Jeddah +966572737505 <> buy cytotec <> unwanted kit Saudi A...Abortion pills in Jeddah +966572737505 <> buy cytotec <> unwanted kit Saudi A...
Abortion pills in Jeddah +966572737505 <> buy cytotec <> unwanted kit Saudi A...samsungultra782445
 
CLASSIFICATION AND PROPERTIES OF FATS AND THEIR FUNCTIONS
CLASSIFICATION AND PROPERTIES OF FATS AND THEIR FUNCTIONSCLASSIFICATION AND PROPERTIES OF FATS AND THEIR FUNCTIONS
CLASSIFICATION AND PROPERTIES OF FATS AND THEIR FUNCTIONSDr. TATHAGAT KHOBRAGADE
 
一比一原版(LMU毕业证书)英国伦敦都市大学毕业证学位证可查学历认证
一比一原版(LMU毕业证书)英国伦敦都市大学毕业证学位证可查学历认证一比一原版(LMU毕业证书)英国伦敦都市大学毕业证学位证可查学历认证
一比一原版(LMU毕业证书)英国伦敦都市大学毕业证学位证可查学历认证funaxa
 
HYDROPONICS cratky method 1234567890qwew
HYDROPONICS  cratky  method 1234567890qwewHYDROPONICS  cratky  method 1234567890qwew
HYDROPONICS cratky method 1234567890qwewRolan Ben Lorono
 
一比一原版卡尔顿大学毕业证(carleton毕业证)学历认证靠谱办理
一比一原版卡尔顿大学毕业证(carleton毕业证)学历认证靠谱办理一比一原版卡尔顿大学毕业证(carleton毕业证)学历认证靠谱办理
一比一原版卡尔顿大学毕业证(carleton毕业证)学历认证靠谱办理hwoudye
 
Food Preservatives Market by Product Type, Distribution Channel, End User 202...
Food Preservatives Market by Product Type, Distribution Channel, End User 202...Food Preservatives Market by Product Type, Distribution Channel, End User 202...
Food Preservatives Market by Product Type, Distribution Channel, End User 202...IMARC Group
 
一比一原版(uOttawa毕业证书)加拿大渥太华大学毕业证如何办理
一比一原版(uOttawa毕业证书)加拿大渥太华大学毕业证如何办理一比一原版(uOttawa毕业证书)加拿大渥太华大学毕业证如何办理
一比一原版(uOttawa毕业证书)加拿大渥太华大学毕业证如何办理hwoudye
 
一比一原版查尔斯特大学毕业证如何办理
一比一原版查尔斯特大学毕业证如何办理一比一原版查尔斯特大学毕业证如何办理
一比一原版查尔斯特大学毕业证如何办理hwoudye
 
原版1:1定制(IC大学毕业证)帝国理工学院大学毕业证国外文凭复刻成绩单#电子版制作#留信入库#多年经营绝对保证质量
原版1:1定制(IC大学毕业证)帝国理工学院大学毕业证国外文凭复刻成绩单#电子版制作#留信入库#多年经营绝对保证质量原版1:1定制(IC大学毕业证)帝国理工学院大学毕业证国外文凭复刻成绩单#电子版制作#留信入库#多年经营绝对保证质量
原版1:1定制(IC大学毕业证)帝国理工学院大学毕业证国外文凭复刻成绩单#电子版制作#留信入库#多年经营绝对保证质量funaxa
 
Medical Foods final.ppt (Regulatory Aspects of Food & Nutraceiticals)
Medical Foods final.ppt (Regulatory Aspects of Food & Nutraceiticals)Medical Foods final.ppt (Regulatory Aspects of Food & Nutraceiticals)
Medical Foods final.ppt (Regulatory Aspects of Food & Nutraceiticals)Lokesh Kothari
 
The Codex Alimentarius Commission (CAC).
The Codex Alimentarius Commission (CAC).The Codex Alimentarius Commission (CAC).
The Codex Alimentarius Commission (CAC).Ravikumar Vaniya
 
FSSAI.ppt Food safety standards act in RAFN
FSSAI.ppt Food safety standards act in RAFNFSSAI.ppt Food safety standards act in RAFN
FSSAI.ppt Food safety standards act in RAFNLokesh Kothari
 

Recently uploaded (17)

LESSON 1 PREPARE AND COOKING MEAT GRADE 10
LESSON 1 PREPARE AND COOKING MEAT GRADE 10LESSON 1 PREPARE AND COOKING MEAT GRADE 10
LESSON 1 PREPARE AND COOKING MEAT GRADE 10
 
PRESTAIR MANUFACTURER OF DISPLAY COUNTER
PRESTAIR MANUFACTURER OF DISPLAY COUNTERPRESTAIR MANUFACTURER OF DISPLAY COUNTER
PRESTAIR MANUFACTURER OF DISPLAY COUNTER
 
如何办理新加坡管理大学毕业证成绩单留信学历认证
如何办理新加坡管理大学毕业证成绩单留信学历认证如何办理新加坡管理大学毕业证成绩单留信学历认证
如何办理新加坡管理大学毕业证成绩单留信学历认证
 
NO1 Top Online Amil Baba in Rawalpindi Contact Number Amil in Rawalpindi Kala...
NO1 Top Online Amil Baba in Rawalpindi Contact Number Amil in Rawalpindi Kala...NO1 Top Online Amil Baba in Rawalpindi Contact Number Amil in Rawalpindi Kala...
NO1 Top Online Amil Baba in Rawalpindi Contact Number Amil in Rawalpindi Kala...
 
Abortion pills in Jeddah +966572737505 <> buy cytotec <> unwanted kit Saudi A...
Abortion pills in Jeddah +966572737505 <> buy cytotec <> unwanted kit Saudi A...Abortion pills in Jeddah +966572737505 <> buy cytotec <> unwanted kit Saudi A...
Abortion pills in Jeddah +966572737505 <> buy cytotec <> unwanted kit Saudi A...
 
CLASSIFICATION AND PROPERTIES OF FATS AND THEIR FUNCTIONS
CLASSIFICATION AND PROPERTIES OF FATS AND THEIR FUNCTIONSCLASSIFICATION AND PROPERTIES OF FATS AND THEIR FUNCTIONS
CLASSIFICATION AND PROPERTIES OF FATS AND THEIR FUNCTIONS
 
Jual Obat Aborsi Sorong, Wa : 0822/2310/9953 Apotik Jual Obat Cytotec Di Sorong
Jual Obat Aborsi Sorong, Wa : 0822/2310/9953 Apotik Jual Obat Cytotec Di SorongJual Obat Aborsi Sorong, Wa : 0822/2310/9953 Apotik Jual Obat Cytotec Di Sorong
Jual Obat Aborsi Sorong, Wa : 0822/2310/9953 Apotik Jual Obat Cytotec Di Sorong
 
一比一原版(LMU毕业证书)英国伦敦都市大学毕业证学位证可查学历认证
一比一原版(LMU毕业证书)英国伦敦都市大学毕业证学位证可查学历认证一比一原版(LMU毕业证书)英国伦敦都市大学毕业证学位证可查学历认证
一比一原版(LMU毕业证书)英国伦敦都市大学毕业证学位证可查学历认证
 
HYDROPONICS cratky method 1234567890qwew
HYDROPONICS  cratky  method 1234567890qwewHYDROPONICS  cratky  method 1234567890qwew
HYDROPONICS cratky method 1234567890qwew
 
一比一原版卡尔顿大学毕业证(carleton毕业证)学历认证靠谱办理
一比一原版卡尔顿大学毕业证(carleton毕业证)学历认证靠谱办理一比一原版卡尔顿大学毕业证(carleton毕业证)学历认证靠谱办理
一比一原版卡尔顿大学毕业证(carleton毕业证)学历认证靠谱办理
 
Food Preservatives Market by Product Type, Distribution Channel, End User 202...
Food Preservatives Market by Product Type, Distribution Channel, End User 202...Food Preservatives Market by Product Type, Distribution Channel, End User 202...
Food Preservatives Market by Product Type, Distribution Channel, End User 202...
 
一比一原版(uOttawa毕业证书)加拿大渥太华大学毕业证如何办理
一比一原版(uOttawa毕业证书)加拿大渥太华大学毕业证如何办理一比一原版(uOttawa毕业证书)加拿大渥太华大学毕业证如何办理
一比一原版(uOttawa毕业证书)加拿大渥太华大学毕业证如何办理
 
一比一原版查尔斯特大学毕业证如何办理
一比一原版查尔斯特大学毕业证如何办理一比一原版查尔斯特大学毕业证如何办理
一比一原版查尔斯特大学毕业证如何办理
 
原版1:1定制(IC大学毕业证)帝国理工学院大学毕业证国外文凭复刻成绩单#电子版制作#留信入库#多年经营绝对保证质量
原版1:1定制(IC大学毕业证)帝国理工学院大学毕业证国外文凭复刻成绩单#电子版制作#留信入库#多年经营绝对保证质量原版1:1定制(IC大学毕业证)帝国理工学院大学毕业证国外文凭复刻成绩单#电子版制作#留信入库#多年经营绝对保证质量
原版1:1定制(IC大学毕业证)帝国理工学院大学毕业证国外文凭复刻成绩单#电子版制作#留信入库#多年经营绝对保证质量
 
Medical Foods final.ppt (Regulatory Aspects of Food & Nutraceiticals)
Medical Foods final.ppt (Regulatory Aspects of Food & Nutraceiticals)Medical Foods final.ppt (Regulatory Aspects of Food & Nutraceiticals)
Medical Foods final.ppt (Regulatory Aspects of Food & Nutraceiticals)
 
The Codex Alimentarius Commission (CAC).
The Codex Alimentarius Commission (CAC).The Codex Alimentarius Commission (CAC).
The Codex Alimentarius Commission (CAC).
 
FSSAI.ppt Food safety standards act in RAFN
FSSAI.ppt Food safety standards act in RAFNFSSAI.ppt Food safety standards act in RAFN
FSSAI.ppt Food safety standards act in RAFN
 

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)