0% found this document useful (0 votes)
43 views7 pages

STUDY MAT XI Dictionary

The document discusses dictionaries in Python. It defines dictionaries as mutable containers that associate keys with values. It compares dictionaries to lists and describes how to create, access, update, delete elements from, and traverse dictionaries. It also discusses built-in dictionary methods like get(), keys(), values(), update(), and clear().

Uploaded by

I am Speed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views7 pages

STUDY MAT XI Dictionary

The document discusses dictionaries in Python. It defines dictionaries as mutable containers that associate keys with values. It compares dictionaries to lists and describes how to create, access, update, delete elements from, and traverse dictionaries. It also discusses built-in dictionary methods like get(), keys(), values(), update(), and clear().

Uploaded by

I am Speed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

DICTIONARIES

What is a dictionary in Python ???


Dictionary is a built-in data type of Python. Dictionary is like a container which
associates keys to values. Dictionary are mutable, unordered collections.

How Dictionary is different from the List ?


Dictionary is different from List in following manner..

1. Dictionary is not a sequence where as lists in sequence


2. Each element in dictionary is a key:value pair.
3.Dictionaries don’t have any index numbers, whereas values of a lists are
associated or identified with the help of its associated index number
4. Keys within a dictionary must be unique, where as index of a list is not given by
user, it is always unique.

How to create a dictionary


To create a dictionary one needs to follow the given syntax

< dictionary-name> = { <key> : < value > , < key > : < value > .........}

Curly brackets indicate the beginning and the end of dictionary

The key and the corresponding value is separated by : colon

Each entry consists of a pair < key : value > separated by a comma

For example

Monthdays={“January”:31,”February”:28,” March”,31, “April” : 30 , “ May” :31 ,


“ June “ : 30 , “July “: 31 , “August “ : 31 , “ September “ : 30 , “ October “: 31 ,
“November “ : 30 , “ December” : 31 }

Please see carefully


Key:value pair Key Value
“January “ : 31 “January “ 31
“February”: 28 “February” 28
Please note: if one gives a mutable type as key, Python gives an error as
“unhashable type “

For example
>>> dict = { [1,2] : “sangeeta”}#error As the key has been given as list
Prepared by :Gajendra S Dhami,PGT CS,LPS south city
Initializing a Dictionary
1. To initialize a dictionary , give key : value pairs , separated by
commas and enclosed in curly braces .....
Result = { “ Abhai “ : 88 , “ Amit “ : 90 , “ Atul” : 95 , “ Deepti “ : 56 }

2. Specify key : value pairs as arguments to dict ( ) function


One can pass keys and values as parameters to the function dict ( ), and create a
dictionary

result=dict(name="amit",per=99)

>>> result

{'name': 'amit', 'per': 99}

3 Specify keys separately and corresponding values separately


In this method , the keys and values are enclosed separately in parentheses and are
given as arguments to the zip( ) function, which is then given as argument of dict ( )

For example

result=dict(zip(("name","per","result"),("Ankita",99,"PASS")))

>>> result

{'name': 'Ankita', 'per': 99, 'result': 'PASS'}

Accessing Elements of a Dictionary


While accessing elements from the dictionary one needs a key. While elements
from the list can be accesed through its index number. To access an element from a
dictionary, follow the given syntax

< dictionary-name > [ < key >]

For example

>>> monthday[“January”]

Python return... 31

>>> print (“there are “ , monthday[“January”] ,” days in January “ )

Prepared by :Gajendra S Dhami,PGT CS,LPS south city


Will print

There are 31 days in January

Traversing a Dictionary
Traversing means accessing and processing each element of a dictionary. To
access each element of a dictionary we take help of Python loop as we do take in List

for < item > in < dictionary > :


Process each element

For example
Monthdays={“January”:31,”February”:28,” March”,31, “April” : 30 , “ May” :31 , “
June “ : 30 , “July “: 31 , “August “ : 31 , “ September “ : 30 , “ October “: 31 ,
“November “ : 30 , “ December” : 31 }

To see all the elements of the ab ove dictionary, we give the following loop

for month in dictionary :

print(month , “:” , Monthdays[month] )

The output will be

January : 31

Febraury : 28

March : 31

April : 30

.....

....

Decemeber : 31

In the above example month is the loop variable, which gets assigned with the keys
of monthdays dictionary , one at a time

Accessing keys or values


To see all the keys in a dictionary in one go, one can write < dictionary>.keys()
and to see all the values in one go , one must write < dictionary>. values ( ) For
example

Prepared by :Gajendra S Dhami,PGT CS,LPS south city


>> week = { “Sunday” : 1 , “Monday “ : 2 , “Tuesday “: 3 , “Wednesday “ : 4 ,
“Thursday “ : 5 , “ Friday “ : 6 , “ Saturday “ : 7 }

>>> week.keys ( )

Will show

dict_keys(['sunday', ' monday '])

to see the values of the dictionary element

>>> week.values ( )

Will show

dict_values([1, 2])

one can also convert the sequence returned by keys ( ) and values ( ) functions by
using list ( ) as shown belo w :

>>> list (week.keys( ))

Will show the following

['sunday', ' monday ']

>>> list ( week.values ( ) )

Will show the following

[1 , 2 ]

Adding Elements to Dictionary


One can add new elements to a dictionary using assignment as per
following syntax. The only issue is , entered key must not already be
available , i.e it must be unique
For example :

< dictionary > [ < key > ] =<value >

result["totalmarks"]=499

>>> result

{'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}

Updating Existing Elements in a Dictionary


Prepared by :Gajendra S Dhami,PGT CS,LPS south city
To update an element’s value is very much similarly to adding a new value in to a
dictionary. In this case too we assign the updated values in to the

key. For example

result["per"]=99.5

>>> result

{'name': 'Ankita', 'per': 99.5, 'result': 'PASS', 'totalmarks': 499}

Deleting Elements from a Dictionary


There are two methods for deleting elements from a dictionary

1. To delete a dictionary element, one can use del command. The syntax for
doing so is as follows
del < dictionary > [ <key>]

For example
result={'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}
>>> del result['result']
>>> result
{'name': 'Ankita', 'per': 99, 'totalmarks': 499}

2. Another method to delete elements from a dictionary is by using pop( ) method


as per the following syntax..
<dictionary>.pop(<key>)

For example
result={'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}
>>> result.pop('per')
99
>>> result
{'name': 'Ankita', 'result': 'PASS', 'totalmarks': 499}

Checking for existence of a key


The existence of an element in a dictionary can be checked with the help of in
and not in operators. The syntax to use these operators is as follows

< key > in < dictionary >

< key > not in < dictionary >


Prepared by :Gajendra S Dhami,PGT CS,LPS south city
The in operator will return true if the given key is present in the dictionary
, otherwise false.

The not in operator will return true if the given key is not present in the
dictionary, otherwise false.

For example
result={'name': 'Ankita', 'result': 'PASS', 'totalmarks': 499}

>>> result={'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}

>>> 'percentage' in result

False

>>> 'percentage' not in result

True

FUNCTIONS AND METHODS WITH DICTIONARY


Python provides some built-in methods and functions to ease our work. They are
as follows

1. len ( ) method
This method is used to tell the length i.e total number of elements present in to
the dictionary. The syntax to use len ( ) method is as follow :
len ( < dictionary> )
for example

>>>result={'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}


>>> len(result)
4
2. clear ( ) method
This method removes all the items from the dictionary and dictionary becomes
empty dictionary after this method. The syntax to use this method is.
<dictionary > . clear ( )
for example
>>>result={'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}
>>> result.clear()
>>> result
{}

Prepared by :Gajendra S Dhami,PGT CS,LPS south city


3. get( ) method
This method is used to get an element in reference to the given key. The
syntax is as follows
< dictionary>.get(key, < message > )
for example
>>> result={'name': 'Ankita', 'per': 99, 'result': 'PASS', 'totalmarks': 499}
>>> result.get('result')
'PASS'
>>> result.get('percentage')
>>> result.get('percentage','wrong key ')
'wrong key '
4. keys( ) method
This method returns all of the keys present in the dictionary as a sequence of keys.
The syntax to use it is as follows
<dictionary> . keys ( ) For
example
>>> result.keys()
dict_keys(['name', 'per', 'result', 'totalmarks'])
5. values( ) method
This method is used to return all the values present in to the dictionary as a
sequence of values. The syntax to use it is as follows
< dictionary> . values () For
example
>>> result.values()
dict_values(['Ankita', 99, 'PASS', 499])
6. update( ) method
This method merges key:value pairs from the new dictionary into the original
dictionary, adding or replacing as needed. The items in the new dictionary are
added to the old one and override any items already there with the same keys. The
syntax is
< dictionary>.update ( < other-dictionary>)
stud1={'name':'ANKUR' , ' CLASS': 'XIIA'}
>>> stud2={'name':' KAVITA','CLASS':'XIIB' ,'RESULT':'PASS'}
>>> stud1.update(stud2)
>>> stud1
{'name': ' KAVITA', ' CLASS': 'XIIA', 'CLASS': 'XIIB', 'RESULT': 'PASS'}

Prepared by :Gajendra S Dhami,PGT CS,LPS south city

You might also like