3 PYTHON DICTIONARIES Lyst1729231943741
3 PYTHON DICTIONARIES Lyst1729231943741
>>> teacher={'Bimlendu':'9470010804','Prakash':'8604774180'}
Notice that:
1. Curly braces mark the beginning and end of the dictionary
2. Each entry (key:value) consists of a pair separated by a colon. The
key and corresponding value is given by writing colon(:) between
them.
3. The key:value pairs are separated by comma.
Internally dictionaries are indexed (i.e.) arranged on the basis of keys.
SOME MORE DICTIONARY DECLRATION
Emptydisctionary={ }
>>>daynumberofweek={"Monday":1, "Tuesday":2, "Wednesday":3,
"Thursday":4,"Friday":5,"Saturday":6,"Sunday":7}
>>> subjectandcode={"Physics":42,"Chemistry":43,
"Mathematics":41, "Biology":44,"Computer
Science":83,"Informatics Practices":65,"English":101,"Hindi":2}
Note:
• Dictionaries are also called Associative Arrays or mappings or hashes.
• Keys of a dictionaries must be of immutable type such as Python string,
Number, a tuple (containing only immutable entry) but list which is mutable
can not be used as keys of a dictionary.
>>>dict2={[2,3]:”abc”} #TypeError: Un-sharable Type ‘list’
ACCESSING OF A DICTIONARY
Its general syntax is
dictionaryname<“key">
EXAMPLE:
>>> subjectandcode["Hindi"]
2
>>> subjectandcode["Computer Science"]
83
>>> subjectandcode["Informatics Practices"]
65
ACCESSING ENTIRE DICTIONARY
>>>dictionaryname
• Mentioning only the dictionary name without any key prints the
entire dictionary.
• If the key in square bracket is used along with dictionaryname
produces the value that matches the key otherwise error is
displayed.
Example:
>>> subjectandcode
{'Physics': 42, 'Chemistry': 43, 'Mathematics': 41, 'Biology': 44, 'Computer
Science': 83, 'Informatics Practices': 65, 'English': 101, 'Hindi': 2}
>>> subjectandcode["Hindi"]
2
ACCESSING ENTIRE DICTIONARY
• A dictionary operation that takes a key and finds the
corresponding value is called lookup.
• To access a particular value of the dictionary the key is provided in
square bracket is in double quote i.e. of string type.
• In python the elements (key:value pairs) are unordered. It means
one can not access elements as per specific order.
• References of keys and values are stored in dictionaries.
• Dictionaries are unordered set of elements, the printed order of
elements may or may not be in the order in which we have stored
them in the dictionary.
Access Dictionary Keys:Value one by one through Loop
>>> for subject in subjectandcode:
print(subject,":",subjectandcode[subject])
Physics : 42
Chemistry : 43
Mathematics : 41
Biology : 44
Computer Science : 83
Informatics Practices : 65
English : 101
Hindi : 2
Accessing Keys and Values
>>> subjectandcode.keys()
dict_keys(['Physics', 'Chemistry', 'Mathematics', 'Biology', 'Computer
Science', 'Informatics Practices', 'English', 'Hindi'])
>>> subjectandcode.values()
dict_values([42, 43, 41, 44, 83, 65, 101, 2])
>>> subjectandcode["Sanskrit"]=122
>>> subjectandcode
Key 2
value 4
Key 3
value 1
Key 4
value 2
<dictionary>[<key>]=<value>
>>> Subject
{'Computer': '083', 'Informatics Practices': '065', 'English': '101'}
>>> Subject["Enlsih"]="001"
>>> Subject
{'Computer': '083', 'Informatics Practices': '065', 'English': ‘001',}
Note: To add and to update the syntax is exactly same but in case adding the Key must be
a new unique key and for updating the key must be an existing key and the value will be
a new value by which the key value have to be changed.
DELETING ELEMENTS FROM DICTIONARY
We can delete element from a dictionary using following two ways
(a) del <dictionary>[<key>]
(b) <dictionary>.pop(<key>)
>>> Subject
{'Computer': '083', 'Informatics Practices': '065', 'English': ‘001',}
>>> del Subject["English"]
>>> Subject
{'Computer': '083', 'Informatics Practices': '065'}
>>> Subject.pop("Computer")
'083‘ # popped key value is returned by pop() function which is displayed
>>> Subject
{'Informatics Practices': '065', 'English': '001'}
>>> del Subject["IP"]
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
del Subject["IP"]
KeyError: 'IP'
CHECKING FOR EXISTING OF A KEY IN DICTIONARY
Usual Membership operator in and not in work with dictionary as well to
check for the presence / absence of a key in the dictionary.
>>> emp={'age':25,"Salary":10000,"name":"sanjay"}
>>> "age“ in emp
True
>>> "name" in emp
True
>>> "basic" in emp
False
>>> "basic" not in emp
True
But if we want to check whether a value is present in a dictionary (called
reverse lookup) we need to write proper code.
DICTIONARY FUNCTIONS AND METHODS
SN METHODS PURPOSE SYNTAX AND EXAMPLE
01. len() Returns length of dictionary len<dictionary>
Example
>>> employee={"Name":"B Kumar","Salary":10000,"Age":45}
>>> employee
{'Name': 'B Kumar', 'Salary': 10000, 'Age': 45}
>>> len(employee)
3
02. clear() Removes all elements of a <dictionary>.clear()
list >>> employee={"Name":"B Kumar","Salary":10000,"Age":45}
>>> employee
{'Name': 'B Kumar', 'Salary': 10000, 'Age': 45}
>>> employee.clear()
>>> employee
{}
clear() function removes all the elements of the dictionary but the dictinary object still
remains in memory.
del command used with dictionary delete dictionary object also,
DICTIONARY FUNCTIONS AND METHODS
SN METHODS PURPOSE SYNTAX AND EXAMPLE
03. get( ) We can get the item with the <dictionary>.get()
given key similar to Example
dictionary[key] >>> Subject={"Computer":"083","Informatics
Practices":"065"}
>>> Subject.get("Computer")
'083'
04. items() Returns all of the items in <dictionary>.items()
the dictionary as a sequence >>> Subject={"Computer":"083","Informatics
Practices":"065"}
>>>subject
>>> Subject
{'Computer': '083', 'Informatics Practices': '065'}
>>> Mylist=Subject.items()
>>> Mylist
dict_items([('Computer', '083'), ('Informatics Practices',
'065')])
DICTIONARY FUNCTIONS AND METHODS
SN METHODS PURPOSE SYNTAX AND EXAMPLE
05. keys() This method returns all <dictionary>.keys()
the keys in the dictionary Example
as a sequence (in the form >>> Subject={"Computer":'083',"IP":'065',"Math":'041'}
of list) >>> Subject
{'Computer': '083', 'IP': '065', 'Math': '041'}
>>> Subject.keys()
dict_keys(['Computer', 'IP', 'Math'])
06. values() This method returns all >>> Subject={"Computer":'083',"IP":'065',"Math":'041'}
the values in the >>> Subject
dictionary as a sequence {'Computer': '083', 'IP': '065', 'Math': '041'}
(in the form of list) >>> Subject.values()
dict_values(['083', '065', '041'])
DICTIONARY FUNCTIONS AND METHODS
SN METHODS PURPOSE SYNTAX AND EXAMPLE
07. update() Merges {key:value} pairs dictionary_to_be_updated.update(dictionary_which_to_be
from the new dictionary into _updated)
the existing dictionary, >>> Subject={"Computer":'083',"IP":'065',"Math":'041'}
adding or replacing as >>> Subject
needed. The items in the {'Computer': '083', 'IP': '065', 'Math': '041'}
new dictionary are added to >>>
the old one override any Science={"Physics":"042","Chemistry":"043","Math":"041"}
items already there with the >>> Science
same keys. {'Physics': '042', 'Chemistry': '043', 'Math': '041'}
>>> Subject.update(Science)
>>> Subject
{'Computer': '083', 'IP': '065', 'Math': '041', 'Physics': '042',
'Chemistry': '043'}