You are on page 1of 27

PYTHON DICTIONARIES

What is Dictionary in python?


● Dictionary is a type of collection in python
● It is an unordered set comma-separated key:value pairs
● A key-value pair is called an item
● A key is separated from its value by a colon(:) and consecutive
items are separated by comma (,)
Creating a Dictionary
● To create a dictionary, the items entered are separated by commas and enclosed in
curly braces.
● The keys in the dictionary must be unique and should be of any immutable data
type, i.e., number, string or tuple
● The values can be repeated and can be of any data type
● Syntax:
○ Dictionary_name = {<key>:<value>,<key>:<value>,….}
● Example:
○ Student={"rno":1,"name":"abhi","marks":48}
● To create an empty dictionary
• Dictionary_name={}
Accessing elements of a dictionary
●The items of a dictionary are accessed via the keys rather than via
their relative
●positions or indices. Each key serves as the index and maps to a
value.
●The following example shows how a dictionary returns the value
corresponding to the given key:
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> dict3['Ram']
89
>>> dict3['Sangeeta']
85
>>> dict3['Shyam']
KeyError: 'Shyam'
Dictionaries are Mutable
● Dictionaries are mutable which implies that the contents of the dictionary
can be changed after it has been created.
● We can add a new item to the dictionary as shown in the following
example:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> dict1['Meena'] = 78
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,'Sangeeta': 85, 'Meena': 78}
● The existing dictionary can be modified by just overwriting the key-
value pair. Example to modify a given item in the dictionary:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
#Marks of Suhel changed to 93.5
>>> dict1['Suhel'] = 93.5
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5,
'Sangeeta': 85}
Operations
● Membership :
○ The membership operator in checks if the key is present in the dictionary and
returns True, else it returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> 'Suhel' in dict1
True
○ The not in operator returns True if the key is not present in the dictionary, else it
returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,'Sangeeta':85}
>>> 'Suhel' not in dict1
False
Traversing a Dictionary
● We can access each item of dictionary using for loop
>>> dict1 ={'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
Method 1
>>> for key in dict1:
print(key,':',dict1[key])

○ Mohan: 95
○ Ram: 89
○ Suhel: 92
○ Sangeeta: 85
● Method 2
>>> for key,value in dict1.items():
print(key,':',value)

○ Mohan: 95
○ Ram: 89
○ Suhel: 92
○ Sangeeta: 85

Dictionary Methods and Built-in functions
● fromkeys(): It is used to create a new dictionary from a sequence
containing all the keys and a common value, which will be assigned to all
the keys
Syntax: dict.fromkeys(<key sequence>,[<value>])
<key sequence> is a python sequence containing the keys for the new
dictionary
<value> is the common value that will be assigned to all the keys
Example:
>>>n=dict.fromkeys([2,4,6,8],100)
>>>n
{2:100,4:100,6:100,8:100}
>>>n1=dict.fromkeys((3,4,5))
>>>n1
{3:None,4:None,5:None}
>>>n2=dict.fromkeys((3,4,5),(6,7,8))
>>>n2
{3:(6,7,8),4:(6,7,8),5:(6,7,8)}
● setdefault() - It inserts a new key:value pair only if the key doesn’t already
exists. If key already exists, it returns the current value of the key
Syntax: dict.setdefault(<key>,<value>)
Example:
>>>marks={1:89,2:75,3:78,4:57}
>>>marks.setdefault(5,98)
98
>>>marks.setdefault(3,85)
78
Marks
{1:89,2:75,3:78,4:57,5:98}
● copy(): it creates a copy of dictionary
● If the values referenced by the keys are immutable, then any changes made in the
copy created with copy() will not be reflected in the original dictionary as the
copied dictionary has own set referencing keys
>>> std={1:’neha’,2:’saima’,3:’anvit’,4:’ana’}
>>>std1=std.copy()
>>>std1
{1:’neha’,2:’saima’,3:’anvit’,4:’ana’}
>>>std1[3]=‘kavita’
>>>std1
{1:’neha’,2:’saima’,3:’kavita’,4:’ana’}
>>>std
{1:’neha’,2:’saima’,3:’anvit’,4:’ana’}
● pop() method : this method removes and returns the dictionary element associated to passed key
Syntax: dict.pop(key,<value>)
<dict> is the dictionary in which key is to be deleted
<key> is the key to be deleted
<value> is the return value/message which will be returned by method
Example:
>>>s={1: [34, 56], 2: [98, 65, 33], 3: [86, 90]}
>>>s.pop(3)
[86, 90]
>>>s
{1: [34, 56], 2: [98, 65, 33]}
>>>s.pop(2)
[98, 65, 33]
>>>s.pop(1,'not found')
[34, 56]
>>>s.pop(2,'key not found')
'key not found'
: This method removes and returns last item entered the
● popitem()

dictionary in the form of a tuple


Syntax:
dict.popitem()
dict is the name of the dictionary from where the last entered item is to
be deleted
Example:
>>>t={1: [54, 56, 45], 2: [98, 65, 33]}
>>>t.popitem()
(2, [98, 65, 33])
● sorted() : This method returns the sorted list of dictionary keys
Syntax:

sorted(<dict>,[reverse=False])
<dict> is the dictionary whose keys are sorted
Reverse argument is optional and when set to True, it returns the keys of
dictionary in descending order. default value of reverse is false
Example
>>>std={1: 'komal',2: 'sai',3: 'hari',4: 'karthik',5: 'shiva',7: 'shivani',8: ‘veena'}
>>>sorted(std)
[1, 2, 3, 4, 5, 7, 8]
>>>sorted(std,reverse=True)
[8, 7, 5, 4, 3, 2, 1]
>>>sorted(std.values())
['hari', 'karthik', 'komal', 'sai', 'shiva', 'shivani', 'veena']
>>>sorted(std.items())
[(1, 'komal'),(2, 'sai'),(3, 'hari'),(4, 'karthik'),(5, 'shiva'),(7, 'shivani'),(8,
'veena')]
>>>sorted(std.keys())
[1, 2, 3, 4, 5, 7, 8]
● max() : This method returns the maximum key value of the given
dictionary
Syntax:
max(<dict>)
<dict> is the dictionary name
Example:
>>>std={1: 'komal',2: 'sai',3: 'hari',4: 'karthik',5: 'shiva',7:
'shivani',8: ‘veena'}
>>>max(std)
8
● min() : This method returns the minimum key value from the given
dictionary
syntax:
min(<dict>
<dict> is the dictionary name
example:
>>>std={1: 'komal',2: 'sai',3: 'hari',4: 'karthik',5: 'shiva',7: 'shivani',8:
‘veena’}
>>>max(std)
1
● Sum() : This method returns sum of keys in the given dictionary
● Syntax:
○ Sum(<dict>)
○ <dict> is the dictionary name
example:
>>>std={1: 'komal',2: 'sai',3: 'hari',4: 'karthik',5: 'shiva',7: 'shivani',8: ‘veena’}
>>>sum(std)
30
Programs
● Count the number of times a character appears in a given string using a dictionary
str=input("enter string:")
char_count=dict()
count=0
for i in str:
if i in char_count:
char_count[i]+=1
else:
char_count[i]=1
print(char_count)
Programs
● Count the number of times a character appears in a given string using a dictionary
str=input("enter string:")
char_count=dict()
count=0
for i in str:
if i in char_count:
char_count[i]+=1
else:
char_count[i]=1
print(char_count)
● create a dictionary with names of employees, their salary and access them

emp=dict()
n=int(input("enter number of employees data you want to store: "))
for i in range(n):
name=input("enter name of employee")
sal=input("enter salary of employee")
emp[name]=sal
for n,s in emp.items():
print(n,s)

You might also like