0% found this document useful (0 votes)
2 views12 pages

Dictionary Complete

A Python dictionary is an unordered collection of key-value pairs, where keys are unique and values can be of any type. Dictionaries are mutable, allowing for the addition, modification, and removal of items, and can be accessed using keys rather than indices. Common operations include checking membership, traversing items, and using built-in methods like len(), clear(), and get() to manipulate the dictionary.

Uploaded by

imdbkindasucks
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)
2 views12 pages

Dictionary Complete

A Python dictionary is an unordered collection of key-value pairs, where keys are unique and values can be of any type. Dictionaries are mutable, allowing for the addition, modification, and removal of items, and can be accessed using keys rather than indices. Common operations include checking membership, traversing items, and using built-in methods like len(), clear(), and get() to manipulate the dictionary.

Uploaded by

imdbkindasucks
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

Dictionary

Python dictionary is an unordered collection/sequence of items. It is a mapping


between a set of keys and a set of values. The key-value pair is called an item. A
key is separated from its value by a colon(:) and consecutive items are separated by
commas. Items in dictionaries are unordered, so we may not get back the data in the
same order in which we had entered the data initially in the dictionary.

A Dictionary in Python works similar to the Telephone directory in a real world. As in


telephone directory, the subscriber’s number gets stored according to his name and
address.. So name becomes a key for reference and Telephone number becomes
the value to be searched for. Similarly in Pyhton too, we have a key-value pair using
dictionary.

Features of Dictionary:

 In a dictionary each key maps a value. The association of a key and a value is
called a key value pair.
 Keys are unique but values may or may not be.
 To create a dictionary, key-value pairs are separated by a comma and are
enclosed in two curly braces { }. In key value pair, each value is separated
from its value by a colon.
 The value of dictionary can be of any type, but the keys must be of an
immutable datatype such as strings, numbers etc.
 Dictionary is mutable, We can add new items in a dictionary or can change
the items of a dictionary.

We can print the individual items usign the key


Creating a Dictionary:

To create a dictionary, the items entered are separated by commas and


enclosed in curly braces. Each item is a key value pair, separated through
colon (:). The keys in the dictionary must be unique and should be of any
immutable data type i.e. number or string. The values can be repeated and
can be of any data type.

Syntax : <dictionary name>={Key1 : Value1, Key2 : Value2 , Key3 :


Value3 , Keyn : Valuen }

Example:
#dict1 is an empty dictionary
>>> dict1 = {}
>>> dict1
{}
Create a dictionary Employee with following specification:

Aman - Manager
Naman - Salesman
Hardik - Clerk
Vansh - C.A

Method 1:
Code :

employee={"Aman" : "Manager" , "Naman" : "Salesman" ,"Hardik" : "Clerk" , "Vansh" : "C.A"}


print(employee)
Output:

{'Aman': 'Manager', 'Naman': 'Salesman', 'Hardik': 'Clerk', 'Vansh': 'C.A'}

Method 2:

Code :

employee=dict() # creates empty dictionary


print(employee)
employee=({"Aman" : "Manager" , "Naman" : "Salesman" ,"Hardik" : "Clerk" , "Vansh" : "C.A"})
print(employee)

Output:

{ } # representing empty dictionary


{'Aman': 'Manager', 'Naman': 'Salesman', 'Hardik': 'Clerk', 'Vansh': 'C.A'}
Method 3:

Code :

employee=dict()
employee["aman"] = "Manager"
employee ["Naman"]= "Salesman"
employee ["Hardik"]= "Clerk"
employee ["Vansh"]= "C.A"
print(employee)

Output:

{'aman': 'Manager', 'Naman': 'Salesman', 'Hardik': 'Clerk', 'Vansh': 'C.A'}

How to access elements in a dictionary?

As we know that the items of string or list are accessed using a technique called
indexing. 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.

Syntax: print(dict[<key>])

Code
employee={"Aman" : "Manager" , "Naman" : "Salesman" ,"Hardik" : "Clerk" , "Vansh" : "C.A"}
print(employee["Hardik"])
Output: Clerk

In the above example the key 'Aman' always maps to the value ‘Manager’ and key
'Hardik' always maps to the value ‘Clerk’. So the order of items does not matter. If
the key is not present in the dictionary we get KeyError.

Membership Operation

The membership operator in checks if the key is present in the dictionary and
returns True, else it returns False.

>>> employee={"Aman" : "Manager" , "Naman" : "Salesman" ,"Hardik" : "Clerk" ,


"Vansh" : "C.A"}
>>> "Naman" in employee
True

>>> "Raman" in employee


False

The not in operator returns True if the key is not present in the dictionary, else
it returns False.

>>> "Raman" not in employee


True

>>> "Naman" not in employee


False

Operations on Dictionary

Dictionaries are mutable which implies that the contents of the dictionary can
be changed after it has been created.
(A) Adding a new item

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}

(B) Modifying an existing item


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}

How to traverse in a dictionary?


Traversing means accessing each element of a dictionary.
Code
emp={"Aman" : "Manager" , "Naman" : "Salesman" ,"Hardik" : "Clerk" , "Vansh" :
"C.A"}
for i in emp:
print(i,"\t\t",emp[i])
Output
Aman Manager
Naman Salesman
Hardik Clerk
Vansh C.A
Appending values in a dictionary :
We can also add new values to the existing dictionaries by:
Synatx:
Dictionary name[key]=value

Updating Elements in a dictionary


We can also update a dictionary for modifying existing key-value pair. It is done in two
ways :
a) If key is present in the dictionary, then it will change the value of that particular key.
b) If key is not there then it will add the key pair value in the dictionary.
Syntax:
Dictionary name[key]=value

Merge other dictionary into existing one:


We can merge other dictionary into existing one by: update () . It merges the keys and
the values of one dictionary into another and overwrites the values of same key.
Syntax:
Dic_name1.update (dic_name2)
Using this dic_name2 is added to dic_name1.

Removing an Item from dictionary:


By using del command or by pop() , we can remove an item from existing dictionary.

Syntax:
del dicname[key]
or
[Link](key)

IN and NOT IN Membership operator:


It checks whether a particular key is present in the dictionary or not. It returns the result
as True or False.
Eg :
Consider a dictionary :
Dict= {Gaurav:44 , Babbu:50 , Saroj:64}
Common methods used with dictionary:

len () : This function counts the number of key value pairs in the dictionary.
Syntax :
len(dict)

clear (): It removes all items from the particular dictionary.


Syntax :
[Link]()
get(): It returns the value for the given key. If key is not available , then returns default
value None.
Syntax:
[Link](key,, default=None)

Items(): This function returns the contents of dictionary as a key value pair.
Syntax:
[Link]()

keys(): This function returns the key from the key-value pairs..
Syntax:
[Link]()

values(): It returns the list of values from the key value pair in a dictionary.
Syntax:
[Link]()
Manipulations on Dictionaries
(a) Create a dictionary ‘ODD’ of odd numbers between 1 and 10, where the key is
the decimal number and the value is the corresponding number in words.

>>> ODD = {1:'One',3:'Three',5:'Five',7:'Seven',9:'Nine'}


>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven', 9: 'Nine'}
(b) Display the keys in dictionary ‘ODD’.

>>> [Link]()
dict_keys([1, 3, 5, 7, 9])
(c) Display the values in dictionary ‘ODD’.

>>> [Link]()
dict_values(['One', 'Three', 'Five', 'Seven', 'Nine'])
(d) Display the items from dictionary ‘ODD’

>>> [Link]()
dict_items([(1, 'One'), (3, 'Three'), (5, 'Five'), (7, 'Seven'), (9, 'Nine')])
(e) Find the length of the dictionary ‘ODD’.

>>> len(ODD)
5
(f) Check if 7 is present or not in dictionary ‘ODD’

>>> 7 in ODD
True

(g) Check if 2 is present or not in dictionary ‘ODD’


>>> 2 in ODD
False
(h) Retrieve the value corresponding to the key 9

>>> [Link](9)
'Nine'
(i) Delete the item from the dictionary, corresponding to the key 9. ‘ODD’

>>> del ODD[9]


>>> ODD
{1: 'One', 3: 'Three', 5: 'Five', 7: 'Seven'}
Consider a dictionary :
Dict= {Gaurav:44 , Babbu:50 , Saroj:64}

Write a code to perform the following:


a) Add one more value Tehri : 70 in dictionary.
b) Change the age of Babbu from 50 to 52.
c) Remove the item Saroj from the dictionary
d) Check whether key Usha, existing in the dictionary or not.

Program Output
dict= {'Gaurav':44 , 'Babbu':50 , 'Saroj':64} {'Gaurav': 44, 'Babbu': 52, 'Tehri': 70}
dict['Tehri']=70 False
dict['Babbu']=52
del dict['Saroj']
print(dict)
print('usha' in dict)

Program to accept the keys and values of a dictionary from the user and print the
same after accepting.

Code Output
mydic=dict() enter the elements of a dictionary
n=int(input("enter the elements of a dictionary ")) 2
for i in range(1,n+1): enter key 1
k=input("enter key ") enter value a
v=input("enter value ") enter key 2
mydic[k]=v enter value b
print("Key","\t\t","Value") Key Value
for i in mydic: 1 a
print(i,"\t\t",mydic[i]) 2 b

Program to enter section name and stream in dictionary classxiI and display the
name of all sections and streams

Program Output
classxii=dict() enter the number of sections 6
n=int(input("enter the number of sections ")) enter Section TOPAZ
for i in range(1,n+1): enter Stream NON MED
sec=input("enter Section ") enter Section EMERALD
st=input("enter Stream ") enter Stream MED
classxi[sec]=st enter Section RUBY
print("Section","\t\t","Stream") enter Stream COMMERCE
for i in classxi: enter Section DIAMOND
print(i,"\t\t",classxi[i]) enter Stream COMMERCE
enter Section PEARL
enter Stream NON MED
enter Section SAPPHIRE
enter Stream HUMANITIES
Section Stream
TOPAZ NON MED
EMERALD MED
RUBY COMMERCE
DIAMOND COMMERCE
PEARL NON MED
SAPPHIRE
HUMANITIES

How to get the name of keys from the dictionary


Keys() is used to get the name of keys from the dictionary Eg:
Syntax:
<Variable name>=<Dictionary name>.keys()

Code Output
mydic=dict() enter the elements of a dictionary 2
n=int(input("enter the elements of a dictionary")) enter key 23
for i in range(1,n+1): enter value yashti
k=input("enter key ") enter key 5
v=input("enter value ") enter value dev
mydic[k]=v dict_keys(['23', '5'])
a=[Link]()
print(a)

Program to create a dictionary containing customer name and their respective


phone numbers. Search the customer name and print the phone number of that
particular customer. Display the detail in two column format.

Program Output
cust=dict() ADD ITEMS IN DICTIONARY- Y/N ??Y
while True: enter name AMIT
enter phone no 234567809
ch=input("ADD ITEMS IN DICTIONARY-Y/N ADD ITEMS IN DICTIONARY- Y/N ??Y
??") enter name SUMIT
if ch=="y" or ch=="Y": enter phone no 9729384208
print("enter name ",end="") ADD ITEMS IN DICTIONARY- Y/N ??Y
name=input() enter name RAVI
enter phone no 2345698765
print("enter phone no ",end="") ADD ITEMS IN DICTIONARY- Y/N ??N
ph=input() enter name whose phoneno. is to search
cust[name]=ph SUMIT
else: phone number of SUMIT
break 9729384208

sname=input("enter name whose phoneno. To


search")
flag=0
ckeys=[Link]()
for i in ckeys:
if i==sname:
flag=1
break
if flag==1:
print("phone number of ",sname,"\t",cust[i])
else:
print("customer not found")

Write a program to enter names of employees and their salaries (for n users )
as input and store them in a dictionary. Here n is to input by the user.

#Program to create a dictionary which stores names of employees


#and their salary
num = int(input("Enter the number of employees whose data to be stored: "))
count = 1
employee = dict() #create an empty dictionary
for count in range (n):
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
print("\n\nEMPLOYEE_NAME\tSALARY")
for k in employee:
print(k,'\t\t',employee[k])
Output:
Enter the number of employees to be stored: 5
Enter the name of the Employee: 'Tarun'
Enter the salary: 12000
Enter the name of the Employee: 'Amina'
Enter the salary: 34000
Enter the name of the Employee: 'Joseph'
Enter the salary: 24000
Enter the name of the Employee: 'Rahul'
Enter the salary: 30000
Enter the name of the Employee: 'Zoya'
Enter the salary: 25000
EMPLOYEE_NAME SALARY
'Tarun' 12000
'Amina' 34000

'Joseph' 24000
'Rahul' 30000
'Zoya' 25000
Write a program to count the number of times a character appears in a given
string.

#Count the number of times a character appears in a given string


st = input("Enter a string: ")
dic = {} #creates an empty dictionary
for ch in st:
if ch in dic: #if next character is already in dic
dic[ch] += 1
else:
dic[ch] = 1 #if ch appears for the first time
for key in dic:
print(key,':',dic[key])
Output:
Enter a string: HelloWorld
H:1
e:1
l:3
o:2
W:1
r:1
d:1
Write a program to convert a number entered by the user into its
corresponding number in words. for example if the input is 876 then the output
should be ‘Eight Seven Six’.

num = input("Enter any number: ") #number is stored as string


#numberNames is a dictionary of digits and corresponding number #names
numberNames = {0:'Zero',1:'One',2:'Two',3:'Three',4:'Four',\
5:'Five',6:'Six',7:'Seven',8:'Eight',9:'Nine'}
result = ''
for ch in num:
key = int(ch) #converts character to integer
value = numberNames[key]

result = result + ' ' + value


print("The number is:",num)
print("The numberName is:",result)
Output:
Enter any number: 6512 ---
The number is: 6512
The numberName is: Six Five One Two

6512

6 – 6 (numeric) 5 – 5(numeric) 1 – 1(numeric) 2 -2 (numeric)

Value=Six value-Five value-One value-Two

Six Five One Two

You might also like