Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
DICTIONARIES
IN PYTHON
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 pythondictionaries are knownasKEY:VALUEpairs.
 Like with English dictionary we search any word for meaning
associated with it, similarly in Python we search for “key” to get
itsassociatedvalue rather thansearching for an index.
Creating a Dictionary
Syntaxto 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 betweencurlybrackets
2
) Eachvaluemustbe paired withkey element
3
) Eachkey-valuepair mustbe separated by comma(,)
Creating a 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 immutabletype suchas:
- Apython string
- A number
- Atuple(containingonly immutable entries)
- If wetry to give mutable type askey,python will give an error
- >>>dict2 = {[2,3]:”abc”} #Error
Accessingelementsof Dictionary
 Toaccess Dictionary elementsweneedthe “key”
>>>mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
>>> mydict['salary']
25000
Note: if youtry to access“key” whichisnot in the dictionary, python
will raise an error
>>>mydict[‘comm’] #Error
Traversing a Dictionary
 Pythonallows to apply “for” loop to traverse every
elementof dictionary based ontheir “key”. Forloop
will get every key of dictionary and wecanaccess
every elementbased ontheir key.
mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
for key in mydict:
print(key,'=',mydict[key])
Accessingkeysand valuessimultaneously
>>> 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 convertthesequence returnedby keys() and values() by using list() as shown below:
>>> list(mydict.keys()) ['empno', 'name',
'dept', 'salary']
>>> list(mydict.values()) [1,
'Shivam', 'sales', 25000]
Characteristics of a Dictionary
 Unordered set
Adictionary isa unorderedsetof 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.Hencethey 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
Eachkeywithindictionary mustbe unique.Howevertwo uniquekeyscanhavesamevalues.
>>> data={1:100, 2:200,3:300,4:200}
 Mutable
Likelists,dictionary are alsomutable.We canchangethevalue of a certain “key” in place
Data[3]=400
>>>Data
So,to changevalueof dictionary theformat is :
◼ DictionaryName[“key” / key]=new_value
Youcannotonlychangebut youcanadd newkey:valuepair:
Working with Dictionaries
 Multiple ways of creating dictionaries
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
Nowwewill add newpair to thisemptydictionary oneby one as:
Alphabets = {}
Alphabets[“a”]=“apple”
Alphabets[“b”]=“boy”
Adding elementsto Dictionary
 Youcanadd newelementto dictionary as:
dictionaryName[“key”]= value
 T
oprint elementsof nesteddictionary isas :
>>> Visitor=
{'Name':'Scott','Address':{'hno':'11A/B','City':'Kanpur','PinCode'
:'208004'}}
>>> Visitor
{'Name': 'Scott', 'Address': {'hno': '11A/B', 'City': 'Kanpur', 'PinCode':
'2080
04'}}
>>> Visitor['Name'] 'Scott'
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}
>>> delD1[2]
>>> D1
1:10,3:20,4:40
• If you trytoremovetheitemwhose key does not
exists, thepython runtimeerror occurs.
• Del D1[5] #Error
pop() elementsfrom Dictionary
dictionaryName.pop([“Key”])
>>> D1 = {1:10,2:20,3:30,4:40}
>>> D1.pop(2)
1:10,3:20,4:40
Note:ifkeypassedtopop()doesn’texiststhenpython
willraiseanexception.
Pop()functionallowsustocustomizedtheerror
messagedisplayedbyuseofwrongkey
pop() elementsfrom Dictionary
>>> d1
{'a': 'apple', 'b': 'ball', 'c': 'caterpillar', 'd': 'dog'}
>>>d1.pop(‘a’)
>>> d1.pop(‘d‘,’Notfound’)
Not found
Dictionary part 1
Dictionary part 1

More Related Content

Dictionary part 1

  • 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 pythondictionaries are knownasKEY:VALUEpairs.  Like with English dictionary we search any word for meaning associated with it, similarly in Python we search for “key” to get itsassociatedvalue rather thansearching for an index.
  • 3. Creating a Dictionary Syntaxto 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 betweencurlybrackets 2 ) Eachvaluemustbe paired withkey element 3 ) Eachkey-valuepair mustbe separated by comma(,)
  • 4. Creating a 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 immutabletype suchas: - Apython string - A number - Atuple(containingonly immutable entries) - If wetry to give mutable type askey,python will give an error - >>>dict2 = {[2,3]:”abc”} #Error
  • 5. Accessingelementsof Dictionary  Toaccess Dictionary elementsweneedthe “key” >>>mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000} >>> mydict['salary'] 25000 Note: if youtry to access“key” whichisnot in the dictionary, python will raise an error >>>mydict[‘comm’] #Error
  • 6. Traversing a Dictionary  Pythonallows to apply “for” loop to traverse every elementof dictionary based ontheir “key”. Forloop will get every key of dictionary and wecanaccess every elementbased ontheir key. mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000} for key in mydict: print(key,'=',mydict[key])
  • 7. Accessingkeysand valuessimultaneously >>> 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 convertthesequence returnedby keys() and values() by using list() as shown below: >>> list(mydict.keys()) ['empno', 'name', 'dept', 'salary'] >>> list(mydict.values()) [1, 'Shivam', 'sales', 25000]
  • 8. Characteristics of a Dictionary  Unordered set Adictionary isa unorderedsetof 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.Hencethey 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 Eachkeywithindictionary mustbe unique.Howevertwo uniquekeyscanhavesamevalues. >>> data={1:100, 2:200,3:300,4:200}  Mutable Likelists,dictionary are alsomutable.We canchangethevalue of a certain “key” in place Data[3]=400 >>>Data So,to changevalueof dictionary theformat is : ◼ DictionaryName[“key” / key]=new_value Youcannotonlychangebut youcanadd newkey:valuepair:
  • 10. Working with Dictionaries  Multiple ways of creating dictionaries 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 Nowwewill add newpair to thisemptydictionary oneby one as: Alphabets = {} Alphabets[“a”]=“apple” Alphabets[“b”]=“boy”
  • 12. Adding elementsto Dictionary  Youcanadd newelementto dictionary as: dictionaryName[“key”]= value  T oprint elementsof nesteddictionary isas : >>> Visitor= {'Name':'Scott','Address':{'hno':'11A/B','City':'Kanpur','PinCode' :'208004'}} >>> Visitor {'Name': 'Scott', 'Address': {'hno': '11A/B', 'City': 'Kanpur', 'PinCode': '2080 04'}} >>> Visitor['Name'] 'Scott'
  • 13. Updating elementsin Dictionary  Dictionaryname[“key”]=value >>> data={1:100, 2:200,3:300,4:200} >>> data[3]=1500 >>> data[3] # 1500
  • 14. Deleting elementsfrom Dictionary del dictionaryName[“Key”] >>> D1 = {1:10,2:20,3:30,4:40} >>> delD1[2] >>> D1 1:10,3:20,4:40 • If you trytoremovetheitemwhose key does not exists, thepython runtimeerror occurs. • Del D1[5] #Error
  • 15. pop() elementsfrom Dictionary dictionaryName.pop([“Key”]) >>> D1 = {1:10,2:20,3:30,4:40} >>> D1.pop(2) 1:10,3:20,4:40 Note:ifkeypassedtopop()doesn’texiststhenpython willraiseanexception. Pop()functionallowsustocustomizedtheerror messagedisplayedbyuseofwrongkey
  • 16. pop() elementsfrom Dictionary >>> d1 {'a': 'apple', 'b': 'ball', 'c': 'caterpillar', 'd': 'dog'} >>>d1.pop(‘a’) >>> d1.pop(‘d‘,’Notfound’) Not found