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")

More Related Content

What's hot (20)

PPTX
C++ string
Dheenadayalan18
 
PDF
Python Collections Tutorial | Edureka
Edureka!
 
PPTX
Modules in Python Programming
sambitmandal
 
PPTX
FLOW OF CONTROL-NESTED IFS IN PYTHON
vikram mahendra
 
PDF
File and directories in python
Lifna C.S
 
PPT
standard template library(STL) in C++
•sreejith •sree
 
DOC
Time and space complexity
Ankit Katiyar
 
PPTX
Generators In Python
Simplilearn
 
PPTX
Chapter 05 classes and objects
Praveen M Jigajinni
 
PDF
Variables & Data Types In Python | Edureka
Edureka!
 
PPTX
Python Libraries and Modules
RaginiJain21
 
PPTX
Looping Statements and Control Statements in Python
PriyankaC44
 
PPS
Wrapper class
kamal kotecha
 
PPSX
Modules and packages in python
TMARAGATHAM
 
PPTX
introduction to python
Jincy Nelson
 
PPTX
Introduction to Python Basics Programming
Collaboration Technologies
 
PPTX
Python: Modules and Packages
Damian T. Gordon
 
PPTX
Python | What is Python | History of Python | Python Tutorial
QA TrainingHub
 
PPT
Unit 3 graph chapter6
DrkhanchanaR
 
PPTX
Python-Classes.pptx
Karudaiyar Ganapathy
 
C++ string
Dheenadayalan18
 
Python Collections Tutorial | Edureka
Edureka!
 
Modules in Python Programming
sambitmandal
 
FLOW OF CONTROL-NESTED IFS IN PYTHON
vikram mahendra
 
File and directories in python
Lifna C.S
 
standard template library(STL) in C++
•sreejith •sree
 
Time and space complexity
Ankit Katiyar
 
Generators In Python
Simplilearn
 
Chapter 05 classes and objects
Praveen M Jigajinni
 
Variables & Data Types In Python | Edureka
Edureka!
 
Python Libraries and Modules
RaginiJain21
 
Looping Statements and Control Statements in Python
PriyankaC44
 
Wrapper class
kamal kotecha
 
Modules and packages in python
TMARAGATHAM
 
introduction to python
Jincy Nelson
 
Introduction to Python Basics Programming
Collaboration Technologies
 
Python: Modules and Packages
Damian T. Gordon
 
Python | What is Python | History of Python | Python Tutorial
QA TrainingHub
 
Unit 3 graph chapter6
DrkhanchanaR
 
Python-Classes.pptx
Karudaiyar Ganapathy
 

Similar to Dictionary in python (20)

PPTX
DICTIONARIES (1).pptx
KalashJain27
 
PPTX
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
sumanthcmcse
 
PPTX
Meaning of Dictionary in python language
PRASHANTMISHRA16761
 
PPTX
Ch 7 Dictionaries 1.pptx
KanchanaRSVVV
 
PPTX
Python Fundamental Data structures: Dictionaries
KanadamKarteekaPavan1
 
PPTX
PYTHON Data structures Fundamentals: DICTIONARIES
KanadamKarteekaPavan1
 
PDF
CHAPTER- 9 PYTHON DICTIONARIES.pdf computer science
Bavish5
 
PPTX
dictionary14 ppt FINAL.pptx
MamtaKaundal1
 
PPTX
Unit4-Basic Concepts and methods of Dictionary.pptx
SwapnaliGawali5
 
PDF
Dictionary part 1
RishuKaul2
 
PDF
Python Dictionary
Soba Arjun
 
PDF
Dictionaries in Python programming for btech students
chandinignits
 
PPTX
Dictionariesasdfghjsdfghjklsdfghjkl.pptx
cjrfailure
 
PDF
Python dictionaries
Krishna Nanda
 
PPTX
Dictionaries.pptx
akshat205573
 
PPT
2 UNIT CH3 Dictionaries v1.ppt
tocidfh
 
PPTX
Session10_Dictionaries.ppggyyyyyyyyyggggggggtx
pawankamal3
 
PPTX
Dictionaries in Python programming language
ssuserbad56d
 
DICTIONARIES (1).pptx
KalashJain27
 
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
sumanthcmcse
 
Meaning of Dictionary in python language
PRASHANTMISHRA16761
 
Ch 7 Dictionaries 1.pptx
KanchanaRSVVV
 
Python Fundamental Data structures: Dictionaries
KanadamKarteekaPavan1
 
PYTHON Data structures Fundamentals: DICTIONARIES
KanadamKarteekaPavan1
 
CHAPTER- 9 PYTHON DICTIONARIES.pdf computer science
Bavish5
 
dictionary14 ppt FINAL.pptx
MamtaKaundal1
 
Unit4-Basic Concepts and methods of Dictionary.pptx
SwapnaliGawali5
 
Dictionary part 1
RishuKaul2
 
Python Dictionary
Soba Arjun
 
Dictionaries in Python programming for btech students
chandinignits
 
Dictionariesasdfghjsdfghjklsdfghjkl.pptx
cjrfailure
 
Python dictionaries
Krishna Nanda
 
Dictionaries.pptx
akshat205573
 
2 UNIT CH3 Dictionaries v1.ppt
tocidfh
 
Session10_Dictionaries.ppggyyyyyyyyyggggggggtx
pawankamal3
 
Dictionaries in Python programming language
ssuserbad56d
 
Ad

More from vikram mahendra (20)

PPTX
Communication skill
vikram mahendra
 
PDF
Python Project On Cosmetic Shop system
vikram mahendra
 
PDF
Python Project on Computer Shop
vikram mahendra
 
PDF
PYTHON PROJECT ON CARSHOP SYSTEM
vikram mahendra
 
PDF
BOOK SHOP SYSTEM Project in Python
vikram mahendra
 
PPTX
FLOWOFCONTROL-IF..ELSE PYTHON
vikram mahendra
 
PPTX
FLOW OF CONTROL-INTRO PYTHON
vikram mahendra
 
PPTX
OPERATOR IN PYTHON-PART1
vikram mahendra
 
PPTX
OPERATOR IN PYTHON-PART2
vikram mahendra
 
PPTX
USE OF PRINT IN PYTHON PART 2
vikram mahendra
 
PPTX
DATA TYPE IN PYTHON
vikram mahendra
 
PPTX
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
vikram mahendra
 
PPTX
USER DEFINE FUNCTIONS IN PYTHON
vikram mahendra
 
PPTX
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
vikram mahendra
 
PPTX
INTRODUCTION TO FUNCTIONS IN PYTHON
vikram mahendra
 
PPTX
Python Introduction
vikram mahendra
 
PPTX
GREEN SKILL[PART-2]
vikram mahendra
 
PPTX
GREEN SKILLS[PART-1]
vikram mahendra
 
PPTX
Entrepreneurial skills
vikram mahendra
 
PPTX
Boolean logic
vikram mahendra
 
Communication skill
vikram mahendra
 
Python Project On Cosmetic Shop system
vikram mahendra
 
Python Project on Computer Shop
vikram mahendra
 
PYTHON PROJECT ON CARSHOP SYSTEM
vikram mahendra
 
BOOK SHOP SYSTEM Project in Python
vikram mahendra
 
FLOWOFCONTROL-IF..ELSE PYTHON
vikram mahendra
 
FLOW OF CONTROL-INTRO PYTHON
vikram mahendra
 
OPERATOR IN PYTHON-PART1
vikram mahendra
 
OPERATOR IN PYTHON-PART2
vikram mahendra
 
USE OF PRINT IN PYTHON PART 2
vikram mahendra
 
DATA TYPE IN PYTHON
vikram mahendra
 
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
vikram mahendra
 
USER DEFINE FUNCTIONS IN PYTHON
vikram mahendra
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
vikram mahendra
 
INTRODUCTION TO FUNCTIONS IN PYTHON
vikram mahendra
 
Python Introduction
vikram mahendra
 
GREEN SKILL[PART-2]
vikram mahendra
 
GREEN SKILLS[PART-1]
vikram mahendra
 
Entrepreneurial skills
vikram mahendra
 
Boolean logic
vikram mahendra
 
Ad

Recently uploaded (20)

PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PDF
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PDF
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPTX
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
PPTX
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
PDF
community health nursing question paper 2.pdf
Prince kumar
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
The dynastic history of the Chahmana.pdf
PrachiSontakke5
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
Lesson 2 - WATER,pH, BUFFERS, AND ACID-BASE.pdf
marvinnbustamante1
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Stereochemistry-Optical Isomerism in organic compoundsptx
Tarannum Nadaf-Mansuri
 
Cultivation practice of Litchi in Nepal.pptx
UmeshTimilsina1
 
community health nursing question paper 2.pdf
Prince kumar
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 

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")