SlideShare a Scribd company logo
1 of 39
DICTIONARIES
KEY
-V
ALUEP
AIR
WHAT IS
DICTIONARY
 It is another collection in Python but with different in way of storing and
accessing. Other collection like list, tuple, string are having an index
associated with every element but Python Dictionary have a “key”
associated with every element. That‟s why python dictionaries are known
asKEY:VALUEpairs.
 Like with English dictionary we search any word for meaning associated
with it, similarly in Python we search for “key” to get its associated value
rather thansearching for an index.
CREATINGA DICTIONARY
Syntax to create dictionary:
dictionary_name = {key1:value,key2:value,….} Example
>>> emp= {"empno":1,"name":"Shahrukh","fee":1500000}
Here Keysare : “empno”, “name” and “fee”
Valuesare: 1, “Shahrukh”, 1500000
Note:
1) Dictionary elementsmustbe between curly brackets
2) Eachvalue mustbe paired with key element
3) Eachkey-value pair mustbe separated by comma(,)
CREATINGA DICTIONARY
 Dict1 = {} # emptydictionary
 DaysInMonth={"Jan":31,"Feb":28,"Mar":31,"Apr":31
"May":31,"Jun":30,"Jul":31,"Aug":31
"Sep":30,"Oct":31,"Nov":30,"Dec":31}
Note: Keysof dictionary mustof immutable type suchas:
- Apython string
- A number
- Atuple(containing only immutable entries)
- If we try to give mutable type askey,python will give an error
- >>>dict2 = {[2,3]:”abc”} #Error
ACCESSINGELEMENTSOF DICTIONARY
 T
oaccessDictionary elementswe need the “key”
>>>mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
>>> mydict['salary']
25000
Note: if you try to access“key” which isnot in the dictionary, python
will raise an error
>>>mydict["comm‟] #Error
TRAVERSINGA DICTIONARY
 Pythonallows to apply “for” loop to traverse every element
of dictionary based ontheir “key”. Forloop will get every
key of dictionary and we canaccess every element based on
their key.
mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
for key in mydict:
print(key,'=',mydict[key])
ACCESSINGKEYSAND VALUES
SIMULTANEOUSLY
>>> mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
>>>mydict.keys()
dict_keys(['empno', 'name', 'dept', 'salary'])
>>>mydict.values()
dict_values([1, 'Shivam', 'sales', 25000])
Wecan convert the sequence returned by keys() and values() by using list() as
shown below:
>>> list(mydict.keys())
['empno', 'name', 'dept', 'salary']
>>> list(mydict.values())
[1, 'Shivam', 'sales', 25000]
CHARACTERISTICSOF A DICTIONARY
 Unordered set
Adictionary isa unordered setof key:valuepair
 Not a sequence
Unlike a string, tuple, and list, a dictionary is not a sequence because it is
unordered set of elements. The sequences are indexed by a range of
ordinal numbers. Hence they are ordered but a dictionary is an
unordered collection
 Indexed by Keys,Not Numbers
Dictionaries are indexed by keys.Keysare immutable type
CHARACTERISTICSOF A DICTIONARY
 Keysmustbeunique
Eachkey within dictionary must be unique. However two unique
keyscanhave samevalues.
>>> data={1:100, 2:200,3:300,4:200}
 Mutable
Likelists, dictionary are also mutable. We canchange the value
of a certain “key” in place
Data[3]=400
>>>Data
So,to change value of dictionary the format is :
 DictionaryName[“key” / key]=new_value
Y
oucannot only change but you canadd newkey:value pair:
WORKING WITH
DICTIONARIES
 Multiple ways of creatingdictionaries
1. Initializing a Dictionary : in this method all the key:value pairs of
dictionary are written collectively separated by commasand enclosed in
curly braces Student={“roll”:1,”name”:”Scott”,”Per”:90}
2. Adding key:value pair to an empty Dictionary : in this method we first
create empty dictionary and then key:value pair are added to it one
pair at a time For example
#Empty dictionary
Alphabets={} Or
Alphabets = dict()
WORKING WITH
DICTIONARIES
 Multiple ways of creating dictionaries
Now we will add newpair to this empty dictionary oneby one
as:
Alphabets = {}
Alphabets[“a”]=“apple”
Alphabets[“b”]=“boy”
3. Creating dictionary from name and value pairs: using the dict() constructor
of dictionary, you can also create dictionary initialized from specified set of keys
and values.Thereare multiple ways to provide keysand value to dict()
(i) Specific key:value pairs askeyword argument to dict()
Student=dict(roll=1,name="scott‟,per=89)
WORKING WITH DICTIONARIES
Multiple ways of creating dictionaries
(ii) Specifycomma-separated key:value pairs
student= dict({"roll‟:1,‟name‟:‟scott‟,‟per‟:89})
(ii)Specify keys separately and corresponding values
separately: in this method keys and values are enclosed
separately in parenthesis and are given as arguments to the
zip() inside dict()
Emp= dict(zip(("empno‟,‟name‟,‟dept‟),(1,‟Scott‟,‟HR‟)))
WORKING WITH DICTIONARIES
 Multiple ways of creating dictionaries
(iv) Specify key:value pairs separately in form of
sequences : in this method one list of tuple argument is
These list or tuple contains individual
passed to dict().
key:value pair
Example:
Emp= dict([„name‟,‟Victor‟],[„dept‟,‟sales‟])
Or
Emp= dict(((„name‟,‟john‟),("dept‟,‟it‟),("sal‟,1200)))
ADDING ELEMENTSTO
DICTIONARY
 Y
oucanadd newelement to dictionary as:
dictionaryName[“key”] = value
 Nesting Dictionaries : you can add dictionary as value inside a
dictionary. Thistype of dictionary knownasnesteddictionary.
 Forexample:
Visitor = {"Name‟: ‟Scott‟,
‟Address‟ :
{"hno‟:‟11A/B‟,‟City‟:‟Kanpur‟,‟PinCode‟:‟208004‟}}
ADDING ELEMENTSTO
DICTIONARY
 T
oprint elements of nested dictionary isas :
>>> Visitor ={'Name':'Scott’,
'Address':{'hno':'11A/B','City':'Kanpur','PinCode’:’208004’}}
>>> Visitor
{'Name': 'Scott', 'Address': {'hno': '11A/B', 'City': 'Kanpur', 'PinCode’:’208004’}}
>>> Visitor['Name'] 'Scott'
>>> Visitor['Address']['City']# to accessnested elements 'Kanpur'
UPDATING ELEMENTSIN
DICTIONARY
 Dictionaryname[“key”]=value
>>> data={1:100, 2:200,3:300,4:200}
>>> data[3]=1500
>>> data[3] # 1500
DELETING ELEMENTSFROM
DICTIONARY
del dictionaryName[“Key”]
>>> D1 = {1:10,2:20,3:30,4:40}
>>> del D1[2]
>>> D1
1:10,3:30,4:40
• If you try toremovetheitem whosekey doesnot
exists,thepythonruntime error occurs.
• Del D1[5] #Error
POP() ELEMENTSFROM
DICTIONARY
dictionaryName.pop([“Key”])
>>> D1 = {1:10,2:20,3:30,4:40}
>>> D1.pop(2) ( will return 20 )
1:10,3:30,4:40
Note: if key passed to pop() doesn‟texists thenpython will raise an
exception.
Pop() functionallows usto customized theerror message displayed
by use of wrong key
POP() ELEMENTSFROM
DICTIONARY
>>> d1
{'a': 'apple', 'b': 'ball', 'c': 'caterpillar', 'd': 'dog'}
>>>d1.pop("a‟)
>>> d1.pop("d“ ,‟Not found‟)
Not found
CHECKINGTHE EXISTENCEOF
KEY
 We cancheckthe existenceof key in dictionary
using“in” and “not in”.
>>>alpha={"a":"apple","b":"boy","c":"cat","d":"dog"}
>>> 'a' inalpha
True
>>>‟e‟ in alpha False
>>>‟e‟ notin alpha
True
CHECKINGTHE EXISTENCEOF
KEY
 If you pass“value” of dictionary to search using“in”
it will return False
>>>‟apple‟in alpha
False
T
osearch for a value we have to search in
dict.values()
>>>‟apple‟ in alpha.values()
PRETTY PRINTING A DICTIONARY
 We generally useprint() to print the dictionary in
python. For e.g.
>>>alpha={"a":"apple","b":"boy","c":"cat","d":"dog"}
>>>print(alpha)
{'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'}
T
o print dictionary in more readable form we usejson
module. i.e. import json and thencall the function
dumps()
PRETTY PRINTING A DICTIONARY
>>>alpha={"a":"apple","b":"boy","c":"cat","d":"dog"}
>>>import json
>>> print(json.dumps(alpha,indent=2))
{
"a": "apple",
"c": "cat",
"b": "boy",
"d": "dog"
}
Counting frequency of elements in a list using
dictionary
 Create an empty dictionary
 T
akeup elementfrom list “listname”
 Checkif thiselementexistsasa key in the dictionary:
If not thenadd {key:value} to dictionary in the form
{list-element:countof listelement}
Before wemoveonto thistopic let usunderstand the function split()
PROGRAMTO COUNTTHEFREQUENCY OF
LIST- ELEMENTUSINGA DICTIONARY
import json
sentence="Python learning isgreat fun 
Pythonisinterpreted language"
words = sentence.split()
d={}
for onein words:
key = one
if key not in d:
count= words.count(key)
d[key]=count
print("Counting frequencies in
listn",words)
print(json.dumps(d,indent=1))
DICTIONARY FUNCTIONSAND METHODS
len() :it return the length of dictionary i.e. the count of
elements(key:value pairs) in dictionary
>>>alpha = {'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'}
>>> len(alpha)
4
clear() :thismethod removesall itemsfrom dictionary and
dictionary becomesempty dictionary
>>>alpha.clear()
>>>alpha # {}
• HOWEVER IF YOU USE“DEL” TO DELETE DICTIONARY IT WILL
REMOVE DICTIONARY FROM MEMORY
• >>>ALPHA = {'A': 'APPLE', 'B': 'BOY', 'C': 'CAT', 'D': 'DOG'}
• >>>DEL ALPHA
• >>>ALPHA #ERROR "ALPHA‟IS NOT DEFINED
• GET() :THIS METHOD IS USED VALUE OF GIVEN KEY,IF KEY NOT
FOUND IT RAISES AN EXCEPTION
>>>alpha.get("b‟)
>>>alpha.get("z‟)
# boy
#Error, nothing will print
>>>ALPHA.GET("Z‟,‟NOT FOUND‟)
NOT FOUND
ITEMS() :THIS METHOD RETURNS ALL THE ITEMS IN THE
DICTIONARY AS SEQUENCE OF (KEY,VALUE)TUPLE
>>>ALPHA = {'A': 'APPLE', 'B': 'BOY', 'C': 'CAT', 'D': 'DOG'}
>>> MYTUPLE = ALPHA.ITEMS()
>>>FOR ITEM IN MYTUPLE:
PRINT(ITEM)
DICTIONARY FUNCTIONSAND
METHODS
>>>alpha = {'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'}
>>> mytuple = alpha.items()
>>>for key,value in mytuple:
print(key,value)
keys() : this method return all the keys in the dictionary asa
sequenceof keys(notin list form)
>>> alpha.keys()
dict_keys(['a', 'b', 'c', 'd'])
DICTIONARY FUNCTIONSAND METHODS
>>>alpha = {'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'}
values(): this methodreturn all the values in the dictionary asa
sequenceof keys(alistform)
>>> alpha.values()
dict_values(['apple', 'boy', 'cat', 'dog'])
Update() method : this method merges the key:value pari from the
new dictionary into original dictionary, adding or replacing as
needed. The items in the new dictionary are added to the old one
and override item
V
s
INO
aD
lr
KU
e
M
a
AR
d
VE
y
RMw
A, P
iG
th
T(CS
t)h
, K
e
V O
s
E
a
FK
m
ANe
PUR
k
&eys.
EXAMPLEOF UPDATE
>>> d1={1:100,2:200,3:300,4:400}
>>> d2={1:111,2:222,5:555,4:444}
>>> d1.update(d2)
>>> d1
{1: 111, 2: 222, 3: 300, 4: 444, 5: 555}
>>>d2
{1: 111, 2: 222, 5: 555, 4: 444}
It isequivalentto:
for key in d2.keys():
d1[key] = d2[key]
Given value is
assigned to each key
fromkeys() : return new dictionary with the given set of
elements asthe keysof thedictionary.
Default value is None
List is assigned to
each key, as the list
updated dictionary
key values are
automatically updated
copy() : asthe namesuggest,it will create a copy of
dictionary.
Popitem() : it will removethe last dictionary item are
return key,value.
max(): thisfunction return highest value in dictionary, this
will
min() : this function return highest value in dictionary, this
will work only if all the values in dictionary is of numeric type.
Sorting the
keys
sorted() : this function is used to sort the key or value of dictionary in either
ascendingor descending order. Bydefault it will sort the keys.
Sorting values in
ascending
Sorting values in
descending
characters appear in dictionary
Programtocounthow many times
PROGRAM TO CREATE DICTIONARY FOR STORING
EMPLOYEE NAMESAND SALARYANDACCESS
THEM
PROGRAM TO CREATE DICTIONARY FOR STORING
EMPLOYEE NAMESAND SALARYANDACCESS
THEM
PROGRAM TO CREATE DICTIONARY FOR STORING
EMPLOYEE NAMESAND SALARYANDACCESS
THEM

More Related Content

Similar to DICTIONARIES (1).pptx

Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
ssuser8e50d8
 
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllfPython-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Meha46
 
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdfC++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
rahulfancycorner21
 

Similar to DICTIONARIES (1).pptx (20)

Lecture-6.pdf
Lecture-6.pdfLecture-6.pdf
Lecture-6.pdf
 
Python Lecture 10
Python Lecture 10Python Lecture 10
Python Lecture 10
 
Dictionaries and Sets
Dictionaries and SetsDictionaries and Sets
Dictionaries and Sets
 
Dictionary.pptx
Dictionary.pptxDictionary.pptx
Dictionary.pptx
 
Ch_13_Dictionary.pptx
Ch_13_Dictionary.pptxCh_13_Dictionary.pptx
Ch_13_Dictionary.pptx
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Python dictionary
Python dictionaryPython dictionary
Python dictionary
 
dataStructuresInPython.pptx
dataStructuresInPython.pptxdataStructuresInPython.pptx
dataStructuresInPython.pptx
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
Farhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionaries
 
Python Sets_Dictionary.pptx
Python Sets_Dictionary.pptxPython Sets_Dictionary.pptx
Python Sets_Dictionary.pptx
 
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
 
Dictionaries.pptx
Dictionaries.pptxDictionaries.pptx
Dictionaries.pptx
 
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllfPython-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Python : Dictionaries
 
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdfC++ code, please help! RESPOND W COMPLETED CODE PLEASE,  am using V.pdf
C++ code, please help! RESPOND W COMPLETED CODE PLEASE, am using V.pdf
 
Python slide.1
Python slide.1Python slide.1
Python slide.1
 
Chap1introppt2php(finally done)
Chap1introppt2php(finally done)Chap1introppt2php(finally done)
Chap1introppt2php(finally done)
 

Recently uploaded

Call Girls Bidadi ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Call Girls Bidadi ☎ 7737669865☎ Book Your One night Stand (Bangalore)Call Girls Bidadi ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Call Girls Bidadi ☎ 7737669865☎ Book Your One night Stand (Bangalore)
amitlee9823
 
Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
amitlee9823
 
Gabriel_Carter_EXPOLRATIONpp.pptx........
Gabriel_Carter_EXPOLRATIONpp.pptx........Gabriel_Carter_EXPOLRATIONpp.pptx........
Gabriel_Carter_EXPOLRATIONpp.pptx........
deejay178
 
一比一原版(毕业证书)意大利米兰理工大学毕业证学位证可查学历认证
一比一原版(毕业证书)意大利米兰理工大学毕业证学位证可查学历认证一比一原版(毕业证书)意大利米兰理工大学毕业证学位证可查学历认证
一比一原版(毕业证书)意大利米兰理工大学毕业证学位证可查学历认证
epodumf6
 
Call Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
amitlee9823
 
0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf
0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf
0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf
ssuserded2d4
 
Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...
Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...
Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...
Pooja Nehwal
 
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
amitlee9823
 
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
amitlee9823
 
Call Girls Brigade Road Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Brigade Road Just Call 👗 7737669865 👗 Top Class Call Girl Service ...Call Girls Brigade Road Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Brigade Road Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
amitlee9823
 
Jual obat aborsi Jakarta ( 085657271886 )Cytote pil telat bulan penggugur kan...
Jual obat aborsi Jakarta ( 085657271886 )Cytote pil telat bulan penggugur kan...Jual obat aborsi Jakarta ( 085657271886 )Cytote pil telat bulan penggugur kan...
Jual obat aborsi Jakarta ( 085657271886 )Cytote pil telat bulan penggugur kan...
ZurliaSoop
 
Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...
Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...
Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...
amitlee9823
 
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
amitlee9823
 

Recently uploaded (20)

Call Girls Bidadi ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Call Girls Bidadi ☎ 7737669865☎ Book Your One night Stand (Bangalore)Call Girls Bidadi ☎ 7737669865☎ Book Your One night Stand (Bangalore)
Call Girls Bidadi ☎ 7737669865☎ Book Your One night Stand (Bangalore)
 
Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Bommanahalli Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
 
Gabriel_Carter_EXPOLRATIONpp.pptx........
Gabriel_Carter_EXPOLRATIONpp.pptx........Gabriel_Carter_EXPOLRATIONpp.pptx........
Gabriel_Carter_EXPOLRATIONpp.pptx........
 
WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Salarpur Sector 81 ( Noida)
 
一比一原版(毕业证书)意大利米兰理工大学毕业证学位证可查学历认证
一比一原版(毕业证书)意大利米兰理工大学毕业证学位证可查学历认证一比一原版(毕业证书)意大利米兰理工大学毕业证学位证可查学历认证
一比一原版(毕业证书)意大利米兰理工大学毕业证学位证可查学历认证
 
Call Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Bidadi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf
0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf
0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf0425-GDSC-TMU.pdf
 
Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...
Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...
Dombivli Call Girls, 9892124323, Kharghar Call Girls, chembur Call Girls, Vas...
 
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hoodi Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Presentation for the country presentation
Presentation for the country presentationPresentation for the country presentation
Presentation for the country presentation
 
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Nandini Layout Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
 
Dubai Call Girls Kiki O525547819 Call Girls Dubai Koko
Dubai Call Girls Kiki O525547819 Call Girls Dubai KokoDubai Call Girls Kiki O525547819 Call Girls Dubai Koko
Dubai Call Girls Kiki O525547819 Call Girls Dubai Koko
 
Pooja 9892124323, Call girls Services and Mumbai Escort Service Near Hotel Sa...
Pooja 9892124323, Call girls Services and Mumbai Escort Service Near Hotel Sa...Pooja 9892124323, Call girls Services and Mumbai Escort Service Near Hotel Sa...
Pooja 9892124323, Call girls Services and Mumbai Escort Service Near Hotel Sa...
 
Call Girls Brigade Road Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Brigade Road Just Call 👗 7737669865 👗 Top Class Call Girl Service ...Call Girls Brigade Road Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
Call Girls Brigade Road Just Call 👗 7737669865 👗 Top Class Call Girl Service ...
 
CFO_SB_Career History_Multi Sector Experience
CFO_SB_Career History_Multi Sector ExperienceCFO_SB_Career History_Multi Sector Experience
CFO_SB_Career History_Multi Sector Experience
 
Jual obat aborsi Jakarta ( 085657271886 )Cytote pil telat bulan penggugur kan...
Jual obat aborsi Jakarta ( 085657271886 )Cytote pil telat bulan penggugur kan...Jual obat aborsi Jakarta ( 085657271886 )Cytote pil telat bulan penggugur kan...
Jual obat aborsi Jakarta ( 085657271886 )Cytote pil telat bulan penggugur kan...
 
Hot Call Girls |Delhi |Janakpuri ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Janakpuri ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Janakpuri ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Janakpuri ☎ 9711199171 Book Your One night Stand
 
Guide to a Winning Interview May 2024 for MCWN
Guide to a Winning Interview May 2024 for MCWNGuide to a Winning Interview May 2024 for MCWN
Guide to a Winning Interview May 2024 for MCWN
 
Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...
Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...
Nagavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore Es...
 
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
Chikkabanavara Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangal...
 

DICTIONARIES (1).pptx

  • 2. WHAT IS DICTIONARY  It is another collection in Python but with different in way of storing and accessing. Other collection like list, tuple, string are having an index associated with every element but Python Dictionary have a “key” associated with every element. That‟s why python dictionaries are known asKEY:VALUEpairs.  Like with English dictionary we search any word for meaning associated with it, similarly in Python we search for “key” to get its associated value rather thansearching for an index.
  • 3. CREATINGA DICTIONARY Syntax to create dictionary: dictionary_name = {key1:value,key2:value,….} Example >>> emp= {"empno":1,"name":"Shahrukh","fee":1500000} Here Keysare : “empno”, “name” and “fee” Valuesare: 1, “Shahrukh”, 1500000 Note: 1) Dictionary elementsmustbe between curly brackets 2) Eachvalue mustbe paired with key element 3) Eachkey-value pair mustbe separated by comma(,)
  • 4. CREATINGA DICTIONARY  Dict1 = {} # emptydictionary  DaysInMonth={"Jan":31,"Feb":28,"Mar":31,"Apr":31 "May":31,"Jun":30,"Jul":31,"Aug":31 "Sep":30,"Oct":31,"Nov":30,"Dec":31} Note: Keysof dictionary mustof immutable type suchas: - Apython string - A number - Atuple(containing only immutable entries) - If we try to give mutable type askey,python will give an error - >>>dict2 = {[2,3]:”abc”} #Error
  • 5. ACCESSINGELEMENTSOF DICTIONARY  T oaccessDictionary elementswe need the “key” >>>mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000} >>> mydict['salary'] 25000 Note: if you try to access“key” which isnot in the dictionary, python will raise an error >>>mydict["comm‟] #Error
  • 6. TRAVERSINGA DICTIONARY  Pythonallows to apply “for” loop to traverse every element of dictionary based ontheir “key”. Forloop will get every key of dictionary and we canaccess every element based on their key. mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000} for key in mydict: print(key,'=',mydict[key])
  • 7. ACCESSINGKEYSAND VALUES SIMULTANEOUSLY >>> mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000} >>>mydict.keys() dict_keys(['empno', 'name', 'dept', 'salary']) >>>mydict.values() dict_values([1, 'Shivam', 'sales', 25000]) Wecan convert the sequence returned by keys() and values() by using list() as shown below: >>> list(mydict.keys()) ['empno', 'name', 'dept', 'salary'] >>> list(mydict.values()) [1, 'Shivam', 'sales', 25000]
  • 8. CHARACTERISTICSOF A DICTIONARY  Unordered set Adictionary isa unordered setof key:valuepair  Not a sequence Unlike a string, tuple, and list, a dictionary is not a sequence because it is unordered set of elements. The sequences are indexed by a range of ordinal numbers. Hence they are ordered but a dictionary is an unordered collection  Indexed by Keys,Not Numbers Dictionaries are indexed by keys.Keysare immutable type
  • 9. CHARACTERISTICSOF A DICTIONARY  Keysmustbeunique Eachkey within dictionary must be unique. However two unique keyscanhave samevalues. >>> data={1:100, 2:200,3:300,4:200}  Mutable Likelists, dictionary are also mutable. We canchange the value of a certain “key” in place Data[3]=400 >>>Data So,to change value of dictionary the format is :  DictionaryName[“key” / key]=new_value Y oucannot only change but you canadd newkey:value pair:
  • 10. WORKING WITH DICTIONARIES  Multiple ways of creatingdictionaries 1. Initializing a Dictionary : in this method all the key:value pairs of dictionary are written collectively separated by commasand enclosed in curly braces Student={“roll”:1,”name”:”Scott”,”Per”:90} 2. Adding key:value pair to an empty Dictionary : in this method we first create empty dictionary and then key:value pair are added to it one pair at a time For example #Empty dictionary Alphabets={} Or Alphabets = dict()
  • 11. WORKING WITH DICTIONARIES  Multiple ways of creating dictionaries Now we will add newpair to this empty dictionary oneby one as: Alphabets = {} Alphabets[“a”]=“apple” Alphabets[“b”]=“boy” 3. Creating dictionary from name and value pairs: using the dict() constructor of dictionary, you can also create dictionary initialized from specified set of keys and values.Thereare multiple ways to provide keysand value to dict() (i) Specific key:value pairs askeyword argument to dict() Student=dict(roll=1,name="scott‟,per=89)
  • 12. WORKING WITH DICTIONARIES Multiple ways of creating dictionaries (ii) Specifycomma-separated key:value pairs student= dict({"roll‟:1,‟name‟:‟scott‟,‟per‟:89}) (ii)Specify keys separately and corresponding values separately: in this method keys and values are enclosed separately in parenthesis and are given as arguments to the zip() inside dict() Emp= dict(zip(("empno‟,‟name‟,‟dept‟),(1,‟Scott‟,‟HR‟)))
  • 13. WORKING WITH DICTIONARIES  Multiple ways of creating dictionaries (iv) Specify key:value pairs separately in form of sequences : in this method one list of tuple argument is These list or tuple contains individual passed to dict(). key:value pair Example: Emp= dict([„name‟,‟Victor‟],[„dept‟,‟sales‟]) Or Emp= dict(((„name‟,‟john‟),("dept‟,‟it‟),("sal‟,1200)))
  • 14. ADDING ELEMENTSTO DICTIONARY  Y oucanadd newelement to dictionary as: dictionaryName[“key”] = value  Nesting Dictionaries : you can add dictionary as value inside a dictionary. Thistype of dictionary knownasnesteddictionary.  Forexample: Visitor = {"Name‟: ‟Scott‟, ‟Address‟ : {"hno‟:‟11A/B‟,‟City‟:‟Kanpur‟,‟PinCode‟:‟208004‟}}
  • 15. ADDING ELEMENTSTO DICTIONARY  T oprint elements of nested dictionary isas : >>> Visitor ={'Name':'Scott’, 'Address':{'hno':'11A/B','City':'Kanpur','PinCode’:’208004’}} >>> Visitor {'Name': 'Scott', 'Address': {'hno': '11A/B', 'City': 'Kanpur', 'PinCode’:’208004’}} >>> Visitor['Name'] 'Scott' >>> Visitor['Address']['City']# to accessnested elements 'Kanpur'
  • 16. UPDATING ELEMENTSIN DICTIONARY  Dictionaryname[“key”]=value >>> data={1:100, 2:200,3:300,4:200} >>> data[3]=1500 >>> data[3] # 1500
  • 17. DELETING ELEMENTSFROM DICTIONARY del dictionaryName[“Key”] >>> D1 = {1:10,2:20,3:30,4:40} >>> del D1[2] >>> D1 1:10,3:30,4:40 • If you try toremovetheitem whosekey doesnot exists,thepythonruntime error occurs. • Del D1[5] #Error
  • 18. POP() ELEMENTSFROM DICTIONARY dictionaryName.pop([“Key”]) >>> D1 = {1:10,2:20,3:30,4:40} >>> D1.pop(2) ( will return 20 ) 1:10,3:30,4:40 Note: if key passed to pop() doesn‟texists thenpython will raise an exception. Pop() functionallows usto customized theerror message displayed by use of wrong key
  • 19. POP() ELEMENTSFROM DICTIONARY >>> d1 {'a': 'apple', 'b': 'ball', 'c': 'caterpillar', 'd': 'dog'} >>>d1.pop("a‟) >>> d1.pop("d“ ,‟Not found‟) Not found
  • 20. CHECKINGTHE EXISTENCEOF KEY  We cancheckthe existenceof key in dictionary using“in” and “not in”. >>>alpha={"a":"apple","b":"boy","c":"cat","d":"dog"} >>> 'a' inalpha True >>>‟e‟ in alpha False >>>‟e‟ notin alpha True
  • 21. CHECKINGTHE EXISTENCEOF KEY  If you pass“value” of dictionary to search using“in” it will return False >>>‟apple‟in alpha False T osearch for a value we have to search in dict.values() >>>‟apple‟ in alpha.values()
  • 22. PRETTY PRINTING A DICTIONARY  We generally useprint() to print the dictionary in python. For e.g. >>>alpha={"a":"apple","b":"boy","c":"cat","d":"dog"} >>>print(alpha) {'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'} T o print dictionary in more readable form we usejson module. i.e. import json and thencall the function dumps()
  • 23. PRETTY PRINTING A DICTIONARY >>>alpha={"a":"apple","b":"boy","c":"cat","d":"dog"} >>>import json >>> print(json.dumps(alpha,indent=2)) { "a": "apple", "c": "cat", "b": "boy", "d": "dog" }
  • 24. Counting frequency of elements in a list using dictionary  Create an empty dictionary  T akeup elementfrom list “listname”  Checkif thiselementexistsasa key in the dictionary: If not thenadd {key:value} to dictionary in the form {list-element:countof listelement} Before wemoveonto thistopic let usunderstand the function split()
  • 25. PROGRAMTO COUNTTHEFREQUENCY OF LIST- ELEMENTUSINGA DICTIONARY import json sentence="Python learning isgreat fun Pythonisinterpreted language" words = sentence.split() d={} for onein words: key = one if key not in d: count= words.count(key) d[key]=count print("Counting frequencies in listn",words) print(json.dumps(d,indent=1))
  • 26. DICTIONARY FUNCTIONSAND METHODS len() :it return the length of dictionary i.e. the count of elements(key:value pairs) in dictionary >>>alpha = {'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'} >>> len(alpha) 4 clear() :thismethod removesall itemsfrom dictionary and dictionary becomesempty dictionary >>>alpha.clear() >>>alpha # {}
  • 27. • HOWEVER IF YOU USE“DEL” TO DELETE DICTIONARY IT WILL REMOVE DICTIONARY FROM MEMORY • >>>ALPHA = {'A': 'APPLE', 'B': 'BOY', 'C': 'CAT', 'D': 'DOG'} • >>>DEL ALPHA • >>>ALPHA #ERROR "ALPHA‟IS NOT DEFINED • GET() :THIS METHOD IS USED VALUE OF GIVEN KEY,IF KEY NOT FOUND IT RAISES AN EXCEPTION >>>alpha.get("b‟) >>>alpha.get("z‟) # boy #Error, nothing will print
  • 28. >>>ALPHA.GET("Z‟,‟NOT FOUND‟) NOT FOUND ITEMS() :THIS METHOD RETURNS ALL THE ITEMS IN THE DICTIONARY AS SEQUENCE OF (KEY,VALUE)TUPLE >>>ALPHA = {'A': 'APPLE', 'B': 'BOY', 'C': 'CAT', 'D': 'DOG'} >>> MYTUPLE = ALPHA.ITEMS() >>>FOR ITEM IN MYTUPLE: PRINT(ITEM)
  • 29. DICTIONARY FUNCTIONSAND METHODS >>>alpha = {'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'} >>> mytuple = alpha.items() >>>for key,value in mytuple: print(key,value) keys() : this method return all the keys in the dictionary asa sequenceof keys(notin list form) >>> alpha.keys() dict_keys(['a', 'b', 'c', 'd'])
  • 30. DICTIONARY FUNCTIONSAND METHODS >>>alpha = {'a': 'apple', 'b': 'boy', 'c': 'cat', 'd': 'dog'} values(): this methodreturn all the values in the dictionary asa sequenceof keys(alistform) >>> alpha.values() dict_values(['apple', 'boy', 'cat', 'dog']) Update() method : this method merges the key:value pari from the new dictionary into original dictionary, adding or replacing as needed. The items in the new dictionary are added to the old one and override item V s INO aD lr KU e M a AR d VE y RMw A, P iG th T(CS t)h , K e V O s E a FK m ANe PUR k &eys.
  • 31. EXAMPLEOF UPDATE >>> d1={1:100,2:200,3:300,4:400} >>> d2={1:111,2:222,5:555,4:444} >>> d1.update(d2) >>> d1 {1: 111, 2: 222, 3: 300, 4: 444, 5: 555} >>>d2 {1: 111, 2: 222, 5: 555, 4: 444} It isequivalentto: for key in d2.keys(): d1[key] = d2[key]
  • 32. Given value is assigned to each key fromkeys() : return new dictionary with the given set of elements asthe keysof thedictionary. Default value is None List is assigned to each key, as the list updated dictionary key values are automatically updated
  • 33. copy() : asthe namesuggest,it will create a copy of dictionary. Popitem() : it will removethe last dictionary item are return key,value. max(): thisfunction return highest value in dictionary, this will
  • 34. min() : this function return highest value in dictionary, this will work only if all the values in dictionary is of numeric type. Sorting the keys sorted() : this function is used to sort the key or value of dictionary in either ascendingor descending order. Bydefault it will sort the keys.
  • 35. Sorting values in ascending Sorting values in descending
  • 36. characters appear in dictionary Programtocounthow many times
  • 37. PROGRAM TO CREATE DICTIONARY FOR STORING EMPLOYEE NAMESAND SALARYANDACCESS THEM
  • 38. PROGRAM TO CREATE DICTIONARY FOR STORING EMPLOYEE NAMESAND SALARYANDACCESS THEM
  • 39. PROGRAM TO CREATE DICTIONARY FOR STORING EMPLOYEE NAMESAND SALARYANDACCESS THEM