Dictionaries in Python are used to store data as key-value pairs. Keys must be unique and immutable, like strings or numbers. Values can be any data type. Dictionaries are created using curly brackets {} and keys are separated from values with a colon. Values can be accessed using their key and dictionaries can be iterated over using a for loop. Dictionaries are mutable and allow adding, updating, and deleting key-value pairs.
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])
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”
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