KEMBAR78
Dictionary in python | PPTX
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")

Dictionary in python

  • 1.
  • 2.
    What is DICTIONARY? ADictionary in Python is the unordered and changeable collection of data values that holds key-value pairs.
  • 3.
    What is Keysand 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 CREATEAND 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 CREATEAND 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 THEDICTIONARY 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 VALUESIN 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 VALUESIN 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 accessthe 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('printingEmployee 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 ind1: 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() Itremove 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() Ita 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() Itreturns 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 returna 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 fromKeysmethod 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 convertthe 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 () Itdelete 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 whethera 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 willgive 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 canupdate 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 canupdate 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")