SlideShare a Scribd company logo
DICTIONARY IN PYTHON
COMPUTER SCIENCE(083)
XII
What is DICTIONARY?
A Dictionary in Python is the unordered and changeable
collection of data values that holds key-value pairs.
What is Keys and values in dictionary?
Let us take one Example: telephone directory
a book listing the names, addresses, and telephone numbers
of subscribers in a particular area.
Keys: are Names of subscribers: Which are immutable / read only
/unable to be changed. And Keys are unique within a dictionary.
Values: are Phone number of subscribers: Which are
mutable / can be updated
Syntax:
dict_name={‘key1’:’value1,’key2’:’value2’,…….,’keyN’:’ValueN’}
Example:
d1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First‘}
Elements of a DICTIONARY enclosed in a curly braces{ },
separated by commas (,) . An item has a key and a corresponding
value that is expressed as a pair (key: value)
Key Key Key
ValuesValues Values
HOW TO DECLARE THE DICTIONARY IN PYTHON:
HOW TO CREATE AND INITIALIZE DICTIONARY
If dictionary is declare empty. d1={ }
Initialize dictionary with value:
If we want to store the values in numbers and keys
to access them in string in a dictionary.
d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4}
If we want to store values in words or string and keys as number:-
d2= {1:‘MON’, 2:‘TUE’,3:’WED’, 4:’THU’,5:’FRI’}
d1=dict()Using function:
HOW TO CREATE AND INITIALIZE DICTIONARY
Example: If we create dictionary with characters as keys
and strings as values
D1={‘R’:’Rainy’,’S’:’Summer’,’W’:’Winter’,’A’:’Autumn’}
Example: If both key and values are integer or number
D1={1:10,2:20,3:30,4:40,5:50}
TO DISPLAY THE DICTIONARY INFORMATION'S
----------------Output-------------
{'One': 1, 'Two': 2, 'Three': 3, 'Four': 4}
----------------Output-------------
{1: 'MON', 2: 'TUE', 3: 'WED', 4: 'THU', 5: 'FRI'}
d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4}
print(d1)
d2= {1:‘MON’, 2:‘TUE’,3:’WED’, 4:’THU’,5:’FRI’}
D1={‘R’:’Rainy’,’S’:’Summer’,’W’:’Winter’,’A’:’Autumn’}
D1={1:10,2:20,3:30,4:40,5:50}
----------------Output-------------
{'R': 'Rainy', 'S': 'Summer', 'W': 'Winter', 'A': 'Autumn’}
----------------Output-------------
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
Keys
Values
Print(D1)
Print(D1)
Keys
Values
ENTER THE VALUES IN A DICTIONARY USING DICT()
METHOD
d1=dict()
d1[1]='A'
d1[2]='B'
d1[3]='C'
d1[4]='D'
print(d1)
---------OUTPUT----------
{1: 'A', 2: 'B', 3: 'C', 4: 'D'}
d1=dict({1:'A',2:'B',3:'C',4:'D'})
print(d1)
---------OUTPUT----------
{1: 'A', 2: 'B', 3: 'C', 4: 'D'}
It’s a Empty
dictionary
variable
ENTER THE VALUES IN A DICTIONARY AT RUNTIME USING LOOP
Method2: To accept the students names as a value and rollno are the keys at the RUNTIME
d1=dict()
x=1
while x<=5:
name=input("Enter the student name:")
d1[x]=name
x=x+1
print(d1)
-----------OUTPUT--------------
Enter the student name:Tina
Enter the student name:Riya
Enter the student name:Mohit
Enter the student name:Rohit
Enter the student name:Tushar
{1: 'Tina', 2: 'Riya', 3: 'Mohit', 4: 'Rohit', 5: 'Tushar'}
d1[x]=name
Values
Key means: x=1,x=2,x=3,x=4,x=5
How to access the Elements in a dictionary?
If we want to access 2 value from the d1, we use key ‘Two’ to access it.
d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4}
print(d1['Two']) OUTPUT:---------2
d2= {1:‘MON’, 2:‘TUE’,3:’WED’, 4:’THU’,5:’FRI’}
print(d1[2]) OUTPUT:----------TUE
If we want to access TUE value from the d2, we use key 3 to access it.
d3={‘R’:’Rainy’,’S’:’Summer’,’W’:’Winter’,’A’:’Autumn’}
print(d1[‘W’]) OUTPUT:----------Winter
If we want to access ‘Winter’ value from the d3, we use key ‘W’ to access it.
Employee = {}
print(type(Employee))
print('printing Employee data ....')
print(Employee)
print('Enter the details of the new employee....');
Employee['Name'] = input('Name: ');
Employee['Age'] = int(input('Age: '));
Employee['salary'] = int(input('Salary: '));
Employee['Company'] = input('Company:');
print('printing the new data');
print(Employee)
Program to accept a record of employee in a dictionary Employee.
<class 'dict'>
printing Employee data ....
{}
Enter the details of the new employee....
Name: john
Age: 45
Salary: 45000
Company: Microsoft
printing the new data
{'Name': 'john', 'Age': 45, 'salary': 45000, 'Company': 'Microsoft'}
------OUTPUT------
d1={'One':1,'Two':2,'Three':3,'Four':4}
====OUTPUT=====
One
Two
Three
Four
Traversing a Dictionary /Loops to access a Dictionary:
Print all key names in the dictionary, one by one:
for x in d1:
print(x) This x display all the key names
d1={'One':1,'Two':2,'Three':3,'Four':4}
for x in d1:
print(d1[x])
---OUTPUT--
1
2
3
4
Loops to access a Dictionary:
Print all values in the dictionary, one by one:
d1={'R':'Rainy','S':'Summer','W':'Winter','A':'Autumn'}
for x in d1:
print(d1[x])
---OUTPUT---
Rainy
Summer
Winter
Autumn
Dictionary functions
len()
clear() It remove all the items from the dictionary
It returns the length of the dictionary means count total number
of key-value pair in a dictionary.
d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4}
print(len(d1))
-----Output------
4
d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4}
d1.clear()
print(d1)
--------OUTPUT-------
{ }
Dictionary functions
keys()
values() It a list of values from a dictionary
It returns a list of the key values in a dictionary.
d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4}
-----Output------
dict_keys(['One', 'Two', 'Three', 'Four'])
d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} --------OUTPUT-------
dict_values([1, 2, 3, 4])
print(d1.keys())
print(d1.values())
Dictionary functions
items() It returns the content of dictionary as a list of tuples having
key-value pairs.
d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4}
-----Output------
dict_items([('One', 1), ('Two', 2), ('Three', 3), ('Four', 4)])
print(d1.items())
get() It return a value for the given key from a dictionary
d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} --OUTPUT---
3
person = {'name': 'Phill', 'age': 22’,Salary’: 40000}
print('Name: ', person.get('name'))
print('Age: ', person.get('age'))
print('Salary: ', person.get(‘Salary'))
Another Example:
--Output--
Name: Phill
Age: 22
Salary: 40000
print(d1.get(‘Three’))
fromkeys() The fromKeys method returns the dictionary with specified
keys and values
studnm = (‘Rajesh', ‘Sumit', ‘Roy', ‘Rik')
info = dict.fromkeys(studnm)
print(info)
-----Output------
{'Rajesh': None, 'Sumit': None, 'Roy': None, 'Rik': None}
studnm = (‘Rajesh', ‘Sumit', ‘Roy', ‘Rik')
marks = (80)
info = dict.fromkeys(studnm,marks)
print(info)
Output:
{'Rajesh': 80, 'Sumit': 80, 'Roy': 80, 'Rik': 80}
Here we convert
the tuple into
dictionary using
fromkeys() method
Keys
Values
fromkeys()
Here we convert the list into dictionary using fromkeys()
method
Create a dictionary from Python List
studnm = [‘Rajesh', ‘Sumit', ‘Roy', ‘Rik‘]
marks = (80)
info = dict.fromkeys(studnm,marks)
print(info)
Output:
{'Rajesh': 80, 'Sumit': 80, 'Roy': 80, 'Rik': 80}
Studnm is a list
that store the
keys
pop()
del () It delete the element from a dictionary but not return it.
It delete the element from a dictionary and return the deleted value.
Removing items from a dictionary
d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4}
del d1[‘Two’]
print(d1) -----Output------
{'One': 1, 'Three': 3, 'Four': 4}
d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4}
print(d1.pop(‘Two’))
Print(d1)
-----Output------
2
{'One': 1, 'Three': 3, 'Four': 4}
It check whether a particular key in a dictionary or not.
There are two operator:
1. in operator 2. not in operator
Membership Testing:
in operator:
It returns true if key
appears in the dictionary,
otherwise returns false.
Example:
d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4}
print(‘Two’ in d1)
----------output-----------
True
Note: it will give
True if value not
exists inside the
tuple
not in operator:
It returns true if key appears in a
dictionary, otherwise returns false.
Example:
d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4}
print(‘Two’ not in d1)
----------output-----------
False
How we can update or modify the
values in dictionary
How example one if we want to change the name from ‘Phill’ to
‘John’ in a dictionary
person = {'name': 'Phill', 'age': 22,'Salary': 40000}
person ['name‘]=‘John’
print(person)
----Output---
{'name': 'John', 'age': 22, 'Salary': 40000}
How we can update or modify the values
in dictionary with the help of if
condition
Example: Enter the name from the user and check its name is ‘Phill’
if yes then change salary of person to 75000
person = {'name': 'Phill', 'age': 22,'Salary': 40000}
If person[‘name’] == ‘Phill’:
person [‘Salary‘]=75000
print(person)
----Output---
{'name': 'John', 'age': 22, 'Salary': 75000}
nm=input("enter name")
Ad

More Related Content

What's hot (20)

6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
Venkateswara Babu Ravipati
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
AkshayAggarwal79
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
Guru Nanak Dev University, Amritsar
 
Python strings
Python stringsPython strings
Python strings
Mohammed Sikander
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
narmadhakin
 
Python GUI Programming
Python GUI ProgrammingPython GUI Programming
Python GUI Programming
RTS Tech
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
Pointers in C
Pointers in CPointers in C
Pointers in C
Monishkanungo
 
Tuple in python
Tuple in pythonTuple in python
Tuple in python
Sharath Ankrajegowda
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
Smit Parikh
 
Constructor and Types of Constructors
Constructor and Types of ConstructorsConstructor and Types of Constructors
Constructor and Types of Constructors
Dhrumil Panchal
 
Recursive Function
Recursive FunctionRecursive Function
Recursive Function
Harsh Pathak
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | Edureka
Edureka!
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
Namespaces
NamespacesNamespaces
Namespaces
Sangeetha S
 
Arrays in c
Arrays in cArrays in c
Arrays in c
vampugani
 
Numeric Data types in Python
Numeric Data types in PythonNumeric Data types in Python
Numeric Data types in Python
jyostna bodapati
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
Mohd Sajjad
 

Similar to Dictionary in python (20)

Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
Pedro Rodrigues
 
2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
tocidfh
 
Session10_Dictionaries.ppggyyyyyyyyyggggggggtx
Session10_Dictionaries.ppggyyyyyyyyyggggggggtxSession10_Dictionaries.ppggyyyyyyyyyggggggggtx
Session10_Dictionaries.ppggyyyyyyyyyggggggggtx
pawankamal3
 
Dictionaries.pptx
Dictionaries.pptxDictionaries.pptx
Dictionaries.pptx
akshat205573
 
cs class 12 project computer science .docx
cs class 12 project computer science  .docxcs class 12 project computer science  .docx
cs class 12 project computer science .docx
AryanSheoran1
 
Lecture-6.pdf
Lecture-6.pdfLecture-6.pdf
Lecture-6.pdf
Bhavya103897
 
Python : Dictionaries
Python : DictionariesPython : Dictionaries
Python : Dictionaries
Emertxe Information Technologies Pvt Ltd
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
omprakashmeena48
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
Dictionary in python Dictionary in python Dictionary in pDictionary in python...Dictionary in python Dictionary in python Dictionary in pDictionary in python...
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
sumanthcmcse
 
Python
PythonPython
Python
Vishal Sancheti
 
PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-
Yoshiki Satotani
 
Python list tuple dictionary .pptx
Python list tuple dictionary       .pptxPython list tuple dictionary       .pptx
Python list tuple dictionary .pptx
miteshchaudhari4466
 
Farhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionaries
Farhana Shaikh
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
Krishna Nanda
 
Unit4-Basic Concepts and methods of Dictionary.pptx
Unit4-Basic Concepts and methods of Dictionary.pptxUnit4-Basic Concepts and methods of Dictionary.pptx
Unit4-Basic Concepts and methods of Dictionary.pptx
SwapnaliGawali5
 
Dictionary
DictionaryDictionary
Dictionary
Pooja B S
 
Class 31: Deanonymizing
Class 31: DeanonymizingClass 31: Deanonymizing
Class 31: Deanonymizing
David Evans
 
Practice_Exercises_Data_Structures.pptx
Practice_Exercises_Data_Structures.pptxPractice_Exercises_Data_Structures.pptx
Practice_Exercises_Data_Structures.pptx
Rahul Borate
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
Megha V
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
Pedro Rodrigues
 
2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
tocidfh
 
Session10_Dictionaries.ppggyyyyyyyyyggggggggtx
Session10_Dictionaries.ppggyyyyyyyyyggggggggtxSession10_Dictionaries.ppggyyyyyyyyyggggggggtx
Session10_Dictionaries.ppggyyyyyyyyyggggggggtx
pawankamal3
 
cs class 12 project computer science .docx
cs class 12 project computer science  .docxcs class 12 project computer science  .docx
cs class 12 project computer science .docx
AryanSheoran1
 
STRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdfSTRING LIST TUPLE DICTIONARY FILE.pdf
STRING LIST TUPLE DICTIONARY FILE.pdf
omprakashmeena48
 
Revision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.docRevision Tour 1 and 2 complete.doc
Revision Tour 1 and 2 complete.doc
SrikrishnaVundavalli
 
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
Dictionary in python Dictionary in python Dictionary in pDictionary in python...Dictionary in python Dictionary in python Dictionary in pDictionary in python...
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
sumanthcmcse
 
PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-PyLecture4 -Python Basics2-
PyLecture4 -Python Basics2-
Yoshiki Satotani
 
Python list tuple dictionary .pptx
Python list tuple dictionary       .pptxPython list tuple dictionary       .pptx
Python list tuple dictionary .pptx
miteshchaudhari4466
 
Farhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionaries
Farhana Shaikh
 
Unit4-Basic Concepts and methods of Dictionary.pptx
Unit4-Basic Concepts and methods of Dictionary.pptxUnit4-Basic Concepts and methods of Dictionary.pptx
Unit4-Basic Concepts and methods of Dictionary.pptx
SwapnaliGawali5
 
Class 31: Deanonymizing
Class 31: DeanonymizingClass 31: Deanonymizing
Class 31: Deanonymizing
David Evans
 
Practice_Exercises_Data_Structures.pptx
Practice_Exercises_Data_Structures.pptxPractice_Exercises_Data_Structures.pptx
Practice_Exercises_Data_Structures.pptx
Rahul Borate
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
Megha V
 
Ad

More from vikram mahendra (20)

Communication skill
Communication skillCommunication skill
Communication skill
vikram mahendra
 
Python Project On Cosmetic Shop system
Python Project On Cosmetic Shop systemPython Project On Cosmetic Shop system
Python Project On Cosmetic Shop system
vikram mahendra
 
Python Project on Computer Shop
Python Project on Computer ShopPython Project on Computer Shop
Python Project on Computer Shop
vikram mahendra
 
PYTHON PROJECT ON CARSHOP SYSTEM
PYTHON PROJECT ON CARSHOP SYSTEMPYTHON PROJECT ON CARSHOP SYSTEM
PYTHON PROJECT ON CARSHOP SYSTEM
vikram mahendra
 
BOOK SHOP SYSTEM Project in Python
BOOK SHOP SYSTEM Project in PythonBOOK SHOP SYSTEM Project in Python
BOOK SHOP SYSTEM Project in Python
vikram mahendra
 
FLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHONFLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHON
vikram mahendra
 
FLOWOFCONTROL-IF..ELSE PYTHON
FLOWOFCONTROL-IF..ELSE PYTHONFLOWOFCONTROL-IF..ELSE PYTHON
FLOWOFCONTROL-IF..ELSE PYTHON
vikram mahendra
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
vikram mahendra
 
OPERATOR IN PYTHON-PART1
OPERATOR IN PYTHON-PART1OPERATOR IN PYTHON-PART1
OPERATOR IN PYTHON-PART1
vikram mahendra
 
OPERATOR IN PYTHON-PART2
OPERATOR IN PYTHON-PART2OPERATOR IN PYTHON-PART2
OPERATOR IN PYTHON-PART2
vikram mahendra
 
USE OF PRINT IN PYTHON PART 2
USE OF PRINT IN PYTHON PART 2USE OF PRINT IN PYTHON PART 2
USE OF PRINT IN PYTHON PART 2
vikram mahendra
 
DATA TYPE IN PYTHON
DATA TYPE IN PYTHONDATA TYPE IN PYTHON
DATA TYPE IN PYTHON
vikram mahendra
 
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
vikram mahendra
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
vikram mahendra
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
vikram mahendra
 
INTRODUCTION TO FUNCTIONS IN PYTHON
INTRODUCTION TO FUNCTIONS IN PYTHONINTRODUCTION TO FUNCTIONS IN PYTHON
INTRODUCTION TO FUNCTIONS IN PYTHON
vikram mahendra
 
Python Introduction
Python IntroductionPython Introduction
Python Introduction
vikram mahendra
 
GREEN SKILL[PART-2]
GREEN SKILL[PART-2]GREEN SKILL[PART-2]
GREEN SKILL[PART-2]
vikram mahendra
 
GREEN SKILLS[PART-1]
GREEN SKILLS[PART-1]GREEN SKILLS[PART-1]
GREEN SKILLS[PART-1]
vikram mahendra
 
Entrepreneurial skills
Entrepreneurial skillsEntrepreneurial skills
Entrepreneurial skills
vikram mahendra
 
Python Project On Cosmetic Shop system
Python Project On Cosmetic Shop systemPython Project On Cosmetic Shop system
Python Project On Cosmetic Shop system
vikram mahendra
 
Python Project on Computer Shop
Python Project on Computer ShopPython Project on Computer Shop
Python Project on Computer Shop
vikram mahendra
 
PYTHON PROJECT ON CARSHOP SYSTEM
PYTHON PROJECT ON CARSHOP SYSTEMPYTHON PROJECT ON CARSHOP SYSTEM
PYTHON PROJECT ON CARSHOP SYSTEM
vikram mahendra
 
BOOK SHOP SYSTEM Project in Python
BOOK SHOP SYSTEM Project in PythonBOOK SHOP SYSTEM Project in Python
BOOK SHOP SYSTEM Project in Python
vikram mahendra
 
FLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHONFLOW OF CONTROL-NESTED IFS IN PYTHON
FLOW OF CONTROL-NESTED IFS IN PYTHON
vikram mahendra
 
FLOWOFCONTROL-IF..ELSE PYTHON
FLOWOFCONTROL-IF..ELSE PYTHONFLOWOFCONTROL-IF..ELSE PYTHON
FLOWOFCONTROL-IF..ELSE PYTHON
vikram mahendra
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
vikram mahendra
 
OPERATOR IN PYTHON-PART1
OPERATOR IN PYTHON-PART1OPERATOR IN PYTHON-PART1
OPERATOR IN PYTHON-PART1
vikram mahendra
 
OPERATOR IN PYTHON-PART2
OPERATOR IN PYTHON-PART2OPERATOR IN PYTHON-PART2
OPERATOR IN PYTHON-PART2
vikram mahendra
 
USE OF PRINT IN PYTHON PART 2
USE OF PRINT IN PYTHON PART 2USE OF PRINT IN PYTHON PART 2
USE OF PRINT IN PYTHON PART 2
vikram mahendra
 
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
vikram mahendra
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
vikram mahendra
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
vikram mahendra
 
INTRODUCTION TO FUNCTIONS IN PYTHON
INTRODUCTION TO FUNCTIONS IN PYTHONINTRODUCTION TO FUNCTIONS IN PYTHON
INTRODUCTION TO FUNCTIONS IN PYTHON
vikram mahendra
 
Ad

Recently uploaded (20)

Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 
Chemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptxChemotherapy of Malignancy -Anticancer.pptx
Chemotherapy of Malignancy -Anticancer.pptx
Mayuri Chavan
 
How to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 PurchaseHow to Manage Amounts in Local Currency in Odoo 18 Purchase
How to Manage Amounts in Local Currency in Odoo 18 Purchase
Celine George
 
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Redesigning Education as a Cognitive Ecosystem: Practical Insights into Emerg...
Leonel Morgado
 
E-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26ASE-Filing_of_Income_Tax.pptx and concept of form 26AS
E-Filing_of_Income_Tax.pptx and concept of form 26AS
Abinash Palangdar
 
All About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdfAll About the 990 Unlocking Its Mysteries and Its Power.pdf
All About the 990 Unlocking Its Mysteries and Its Power.pdf
TechSoup
 
Ajanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of HistoryAjanta Paintings: Study as a Source of History
Ajanta Paintings: Study as a Source of History
Virag Sontakke
 
Search Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo SlidesSearch Matching Applicants in Odoo 18 - Odoo Slides
Search Matching Applicants in Odoo 18 - Odoo Slides
Celine George
 
The role of wall art in interior designing
The role of wall art in interior designingThe role of wall art in interior designing
The role of wall art in interior designing
meghaark2110
 
puzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tensepuzzle Irregular Verbs- Simple Past Tense
puzzle Irregular Verbs- Simple Past Tense
OlgaLeonorTorresSnch
 
Myopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduateMyopathies (muscle disorders) for undergraduate
Myopathies (muscle disorders) for undergraduate
Mohamed Rizk Khodair
 
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...Transform tomorrow: Master benefits analysis with Gen AI today webinar,  30 A...
Transform tomorrow: Master benefits analysis with Gen AI today webinar, 30 A...
Association for Project Management
 
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
How to Clean Your Contacts Using the Deduplication Menu in Odoo 18
Celine George
 
Final Evaluation.docx...........................
Final Evaluation.docx...........................Final Evaluation.docx...........................
Final Evaluation.docx...........................
l1bbyburrell
 
spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)spinal cord disorders (Myelopathies and radiculoapthies)
spinal cord disorders (Myelopathies and radiculoapthies)
Mohamed Rizk Khodair
 
How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18How to Configure Public Holidays & Mandatory Days in Odoo 18
How to Configure Public Holidays & Mandatory Days in Odoo 18
Celine George
 
*"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"**"Sensing the World: Insect Sensory Systems"*
*"Sensing the World: Insect Sensory Systems"*
Arshad Shaikh
 
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon DolabaniHistory Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
History Of The Monastery Of Mor Gabriel Philoxenos Yuhanon Dolabani
fruinkamel7m
 
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
Mental Health Assessment in 5th semester bsc. nursing and also used in 2nd ye...
parmarjuli1412
 
Module 1: Foundations of Research
Module 1: Foundations of ResearchModule 1: Foundations of Research
Module 1: Foundations of Research
drroxannekemp
 
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptxU3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
U3 ANTITUBERCULAR DRUGS Pharmacology 3.pptx
Mayuri Chavan
 

Dictionary in python

  • 1. DICTIONARY IN PYTHON COMPUTER SCIENCE(083) XII
  • 2. What is DICTIONARY? A Dictionary in Python is the unordered and changeable collection of data values that holds key-value pairs.
  • 3. What is Keys and values in dictionary? Let us take one Example: telephone directory a book listing the names, addresses, and telephone numbers of subscribers in a particular area. Keys: are Names of subscribers: Which are immutable / read only /unable to be changed. And Keys are unique within a dictionary. Values: are Phone number of subscribers: Which are mutable / can be updated
  • 4. Syntax: dict_name={‘key1’:’value1,’key2’:’value2’,…….,’keyN’:’ValueN’} Example: d1 = {'Name': 'Zara', 'Age': 7, 'Class': 'First‘} Elements of a DICTIONARY enclosed in a curly braces{ }, separated by commas (,) . An item has a key and a corresponding value that is expressed as a pair (key: value) Key Key Key ValuesValues Values HOW TO DECLARE THE DICTIONARY IN PYTHON:
  • 5. HOW TO CREATE AND INITIALIZE DICTIONARY If dictionary is declare empty. d1={ } Initialize dictionary with value: If we want to store the values in numbers and keys to access them in string in a dictionary. d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} If we want to store values in words or string and keys as number:- d2= {1:‘MON’, 2:‘TUE’,3:’WED’, 4:’THU’,5:’FRI’} d1=dict()Using function:
  • 6. HOW TO CREATE AND INITIALIZE DICTIONARY Example: If we create dictionary with characters as keys and strings as values D1={‘R’:’Rainy’,’S’:’Summer’,’W’:’Winter’,’A’:’Autumn’} Example: If both key and values are integer or number D1={1:10,2:20,3:30,4:40,5:50}
  • 7. TO DISPLAY THE DICTIONARY INFORMATION'S ----------------Output------------- {'One': 1, 'Two': 2, 'Three': 3, 'Four': 4} ----------------Output------------- {1: 'MON', 2: 'TUE', 3: 'WED', 4: 'THU', 5: 'FRI'} d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} print(d1) d2= {1:‘MON’, 2:‘TUE’,3:’WED’, 4:’THU’,5:’FRI’}
  • 8. D1={‘R’:’Rainy’,’S’:’Summer’,’W’:’Winter’,’A’:’Autumn’} D1={1:10,2:20,3:30,4:40,5:50} ----------------Output------------- {'R': 'Rainy', 'S': 'Summer', 'W': 'Winter', 'A': 'Autumn’} ----------------Output------------- {1: 10, 2: 20, 3: 30, 4: 40, 5: 50} Keys Values Print(D1) Print(D1) Keys Values
  • 9. ENTER THE VALUES IN A DICTIONARY USING DICT() METHOD d1=dict() d1[1]='A' d1[2]='B' d1[3]='C' d1[4]='D' print(d1) ---------OUTPUT---------- {1: 'A', 2: 'B', 3: 'C', 4: 'D'} d1=dict({1:'A',2:'B',3:'C',4:'D'}) print(d1) ---------OUTPUT---------- {1: 'A', 2: 'B', 3: 'C', 4: 'D'} It’s a Empty dictionary variable
  • 10. ENTER THE VALUES IN A DICTIONARY AT RUNTIME USING LOOP Method2: To accept the students names as a value and rollno are the keys at the RUNTIME d1=dict() x=1 while x<=5: name=input("Enter the student name:") d1[x]=name x=x+1 print(d1) -----------OUTPUT-------------- Enter the student name:Tina Enter the student name:Riya Enter the student name:Mohit Enter the student name:Rohit Enter the student name:Tushar {1: 'Tina', 2: 'Riya', 3: 'Mohit', 4: 'Rohit', 5: 'Tushar'} d1[x]=name Values Key means: x=1,x=2,x=3,x=4,x=5
  • 11. How to access the Elements in a dictionary? If we want to access 2 value from the d1, we use key ‘Two’ to access it. d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} print(d1['Two']) OUTPUT:---------2 d2= {1:‘MON’, 2:‘TUE’,3:’WED’, 4:’THU’,5:’FRI’} print(d1[2]) OUTPUT:----------TUE If we want to access TUE value from the d2, we use key 3 to access it. d3={‘R’:’Rainy’,’S’:’Summer’,’W’:’Winter’,’A’:’Autumn’} print(d1[‘W’]) OUTPUT:----------Winter If we want to access ‘Winter’ value from the d3, we use key ‘W’ to access it.
  • 12. Employee = {} print(type(Employee)) print('printing Employee data ....') print(Employee) print('Enter the details of the new employee....'); Employee['Name'] = input('Name: '); Employee['Age'] = int(input('Age: ')); Employee['salary'] = int(input('Salary: ')); Employee['Company'] = input('Company:'); print('printing the new data'); print(Employee) Program to accept a record of employee in a dictionary Employee. <class 'dict'> printing Employee data .... {} Enter the details of the new employee.... Name: john Age: 45 Salary: 45000 Company: Microsoft printing the new data {'Name': 'john', 'Age': 45, 'salary': 45000, 'Company': 'Microsoft'} ------OUTPUT------
  • 13. d1={'One':1,'Two':2,'Three':3,'Four':4} ====OUTPUT===== One Two Three Four Traversing a Dictionary /Loops to access a Dictionary: Print all key names in the dictionary, one by one: for x in d1: print(x) This x display all the key names
  • 14. d1={'One':1,'Two':2,'Three':3,'Four':4} for x in d1: print(d1[x]) ---OUTPUT-- 1 2 3 4 Loops to access a Dictionary: Print all values in the dictionary, one by one: d1={'R':'Rainy','S':'Summer','W':'Winter','A':'Autumn'} for x in d1: print(d1[x]) ---OUTPUT--- Rainy Summer Winter Autumn
  • 15. Dictionary functions len() clear() It remove all the items from the dictionary It returns the length of the dictionary means count total number of key-value pair in a dictionary. d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} print(len(d1)) -----Output------ 4 d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} d1.clear() print(d1) --------OUTPUT------- { }
  • 16. Dictionary functions keys() values() It a list of values from a dictionary It returns a list of the key values in a dictionary. d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} -----Output------ dict_keys(['One', 'Two', 'Three', 'Four']) d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} --------OUTPUT------- dict_values([1, 2, 3, 4]) print(d1.keys()) print(d1.values())
  • 17. Dictionary functions items() It returns the content of dictionary as a list of tuples having key-value pairs. d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} -----Output------ dict_items([('One', 1), ('Two', 2), ('Three', 3), ('Four', 4)]) print(d1.items())
  • 18. get() It return a value for the given key from a dictionary d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} --OUTPUT--- 3 person = {'name': 'Phill', 'age': 22’,Salary’: 40000} print('Name: ', person.get('name')) print('Age: ', person.get('age')) print('Salary: ', person.get(‘Salary')) Another Example: --Output-- Name: Phill Age: 22 Salary: 40000 print(d1.get(‘Three’))
  • 19. fromkeys() The fromKeys method returns the dictionary with specified keys and values studnm = (‘Rajesh', ‘Sumit', ‘Roy', ‘Rik') info = dict.fromkeys(studnm) print(info) -----Output------ {'Rajesh': None, 'Sumit': None, 'Roy': None, 'Rik': None} studnm = (‘Rajesh', ‘Sumit', ‘Roy', ‘Rik') marks = (80) info = dict.fromkeys(studnm,marks) print(info) Output: {'Rajesh': 80, 'Sumit': 80, 'Roy': 80, 'Rik': 80} Here we convert the tuple into dictionary using fromkeys() method Keys Values
  • 20. fromkeys() Here we convert the list into dictionary using fromkeys() method Create a dictionary from Python List studnm = [‘Rajesh', ‘Sumit', ‘Roy', ‘Rik‘] marks = (80) info = dict.fromkeys(studnm,marks) print(info) Output: {'Rajesh': 80, 'Sumit': 80, 'Roy': 80, 'Rik': 80} Studnm is a list that store the keys
  • 21. pop() del () It delete the element from a dictionary but not return it. It delete the element from a dictionary and return the deleted value. Removing items from a dictionary d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} del d1[‘Two’] print(d1) -----Output------ {'One': 1, 'Three': 3, 'Four': 4} d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} print(d1.pop(‘Two’)) Print(d1) -----Output------ 2 {'One': 1, 'Three': 3, 'Four': 4}
  • 22. It check whether a particular key in a dictionary or not. There are two operator: 1. in operator 2. not in operator Membership Testing: in operator: It returns true if key appears in the dictionary, otherwise returns false. Example: d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} print(‘Two’ in d1) ----------output----------- True
  • 23. Note: it will give True if value not exists inside the tuple not in operator: It returns true if key appears in a dictionary, otherwise returns false. Example: d1={‘One’:1,’Two’:2,’Three’:3,’Four’:4} print(‘Two’ not in d1) ----------output----------- False
  • 24. How we can update or modify the values in dictionary How example one if we want to change the name from ‘Phill’ to ‘John’ in a dictionary person = {'name': 'Phill', 'age': 22,'Salary': 40000} person ['name‘]=‘John’ print(person) ----Output--- {'name': 'John', 'age': 22, 'Salary': 40000}
  • 25. How we can update or modify the values in dictionary with the help of if condition Example: Enter the name from the user and check its name is ‘Phill’ if yes then change salary of person to 75000 person = {'name': 'Phill', 'age': 22,'Salary': 40000} If person[‘name’] == ‘Phill’: person [‘Salary‘]=75000 print(person) ----Output--- {'name': 'John', 'age': 22, 'Salary': 75000} nm=input("enter name")
  翻译: