What is Dictionary:
- Dictionary is a collection of key-value pairs.It is used to store the data in a key-value pairs.It is used to store the data in key-value format.
- Dictionaries are indexed by keys.
- Dictionary is the data type in python.
- Dictionaries are mutable.So we can perform add/delete/modify operations on a dictionary.
- The keys must be a single element in dictionary.
- The values can be any type such as list,tuple,integer etc.
- Dictionaries are also known as maps or associative arrays.
- The keys in a dictionary must must be unique and immutable.So number,strings and tuples can be used as keys.
- Though key values are unique,different keys may have same value.
Creating the dictionary
e.g.
dict={}#create empty dictionary
student={'101':"Ram",'102':"Rames",'103':"Sita",'101':"Sachin",}
employee={1:"Rajesh",2:"Kiran",3:"Morgon",4:"David"}
print(type(dict))
print(type(student))
print(type(employee))
print(student)
print(employee)
Output:-<class 'dict'>
<class 'dict'>
<class 'dict'>
{'101': 'Sachin', '102': 'Rames', '103': 'Sita'}
{1: 'Rajesh', 2: 'Kiran', 3: 'Morgon', 4: 'David'}
>>>
Descriptions:-
- In student dictionary key values are '101','102','103','104' which are a string value and unique in given dictionary We already know that string are immutable.
- In employee dictionary key values are numeric number 1,2,3,4 which are unique and immutable.
Creating dictionary using built-in function dict() :-
Python provides the built-in function dict() which is used to create the dictionary as shown below:-
e.g.
student={}#create empty dictionary
print(student)
student=dict({'101':"Horse",'102':"Lion",'103':"Cow",'104':"Dog"})
print(student)
Output:-
{}
{'101': 'Horse', '102': 'Lion', '103': 'Cow', '104': 'Dog'}
>>>
Creating dictionary using dict() method with each item as a pair:-
e.g.
employee=dict([(1,'ram'),(2,'sita'),(3,'sachin'),(4,'neha')])
print(employee)
Output:-
{1: 'ram', 2: 'sita', 3: 'sachin', 4: 'neha'}
>>>
Creating dictionary using dict() method with the help of list:-
e.g.
list1=[10,20,30,40,50]
number=dict.fromkeys(list1,400) #all values set to 400
print(number)
Output:-
{10: 400, 20: 400, 30: 400, 40: 400, 50: 400}
>>>
Accessing the dictionary elements
- Dictionary element can be accessed using key as an index.
emp={'A101':'Ram','A102':'kiran','A103':'Neha','A104':'shyam',}
print(emp['A101'])
print(emp['A102'])
print(emp['A103'])
print(emp['A104'])
Output:-
Ram
kiran
Neha
shyam
>>>
- Dictionary can be iterated over in three ways:-
e.g.
student={'Name':'Ramesh','Age':30,'Salary':30000,'Company':'MNT LAB'}
#Iterate over key-value pairs
print("Iterate over key-value pairs...")
for k,v in student.items():
print(k,v)
#iterate over keys
print(" ")
print("iterate over keys....")
for k in student.keys():
print(k)
#iterate over keys-shorter way
print(" ")
print("iterate over keys-shorter way...")
for k in student:
print(k)
#iterate over values
print(" ")
print("iterate over values....")
for v in student.values():
print(v)
Output:-
Iterate over key-value pairs...
Name Ramesh
Age 30
Salary 30000
Company MNT LAB
iterate over keys....
Name
Age
Salary
Company
iterate over keys-shorter way...
Name
Age
Salary
Company
iterate over values....
Ramesh
30
30000
MNT LAB
>>>
- Dictionaries are mutable .so we can perform add,delete and modify operations on a dictionary.Dictionaries values can be updated using the specific keys.
- In dictionary update() method is used to update on existing value.If the key-value pair already present in dictionary,the value gets updated otherwise new key-value added in the dictionary.
e.g.
#creating empty dictionary
emp={}
print(emp)
#adding elements in dictionary
emp[0]='Ram'
emp[1]='Sita'
emp[2]='Karan'
emp[3]='Sachin'
emp[4]='Rajesh'
emp[5]='Suresh'
print("printing the dictionary after addition..")
print(emp)
print(" ")
#Adding set of values using single key that is not present in emp dictionary
emp['company']='MNT','HP','HCL','WIPRO'
print("printing the dictionary after extra element in dictionary")
print(emp)
print(" ")
#Updating the existing key values
print("Printing after updating key value")
emp[0]='Sachin'
emp[3]='Manish'
print(emp)
print(" ")
#deleting the dictionary element using del keyword
print("deleting the dictionary element using del keyword")
del emp['company']
print("Printing after delete the some emp data...")
print(emp)
del(emp)
print("Printing after delete the complete emp data...")
print(emp)
Output:-
{}
printing the dictionary after addition..
{0: 'Ram', 1: 'Sita', 2: 'Karan', 3: 'Sachin', 4: 'Rajesh', 5: 'Suresh'}
printing the dictionary after extra element in dictionary
{0: 'Ram', 1: 'Sita', 2: 'Karan', 3: 'Sachin', 4: 'Rajesh', 5: 'Suresh', 'company': ('MNT', 'HP', 'HCL', 'WIPRO')}
Printing after updating key value
{0: 'Sachin', 1: 'Sita', 2: 'Karan', 3: 'Manish', 4: 'Rajesh', 5: 'Suresh', 'company': ('MNT', 'HP', 'HCL', 'WIPRO')}
deleting the dictionary element using del keyword
Printing after delete the some emp data...
{0: 'Sachin', 1: 'Sita', 2: 'Karan', 3: 'Manish', 4: 'Rajesh', 5: 'Suresh'}
Printing after delete the complete emp data...
Traceback (most recent call last):
File "C:\Users\RAMASHANKER VERMA\Desktop\dictionary.py", line 33, in <module>
print(emp)
NameError: name 'emp' is not defined
- Deleting the dictionary values using pop() method.
student={1:'HCL',2:'NOKIA',3:'SUMSANG',4:'Wipro',5:'Microsoft',101:'HP'}
print(student)
#deleting keys using pop() method
student.pop(2)
student.pop(101)
print(student)
Output:-
{1: 'HCL', 2: 'NOKIA', 3: 'SUMSANG', 4: 'Wipro', 5: 'Microsoft', 101: 'HP'}
{1: 'HCL', 3: 'SUMSANG', 4: 'Wipro', 5: 'Microsoft'}
>>>
Note:-pop() method accepts key as a argument and remove the associated value.
- len(dict):-It returns number of key-value pairs(length of dictionary).
student={1:'HCL',2:'NOKIA',3:'SUMSANG',4:'Wipro',5:'Microsoft',101:'HP'}
a=len(student)
print(a)
Output:-
6
>>>
- max(dict):-It returns maximum key-value in dictionary.
e.g.
student={1:'HCL',2:'NOKIA',3:'SUMSANG',4:'Wipro',5:'Microsoft',101:'HP'}
a=len(student)
print(a)
Output:-
101
>>>
- min(dict):-It returns minimum key-value in dictionary.
e.g.
student={1:'HCL',2:'NOKIA',3:'SUMSANG',4:'Wipro',5:'Microsoft',101:'HP'}
a=min(student)
print(a)
Output:-
1
>>>
- str(dict):-It is used to convert the dictionary into printable string.
e.g.
student={1:'HCL',2:'NOKIA',3:'SUMSANG',4:'Wipro',5:'Microsoft',101:'HP'}
a=str(student)
print(a)
Output:-
{1: 'HCL', 2: 'NOKIA', 3: 'SUMSANG', 4: 'Wipro', 5: 'Microsoft', 101: 'HP'}
>>>
- cmp(dict1,dict2):-It is used to compare the number of items of both dictionary.It return True ,if the number of values of first dictionary are greater than the second dictionary otherwise it returns False. cmp not supported in python 3.0 and above version.
Dictionary Functions:-
There are many dictionary methods.Many of the operations performed by them can also be performed by the built-in functions.The useful dictionary function are shown below:-
- dict.clear():-It is used to clear all the dictionary values.
dict1={101:'Ram',102:'Sachin',103:'sita',104:'devid'}
dict1.clear()
print(dict1)
Output:-
{}
>>>
- dict.copy():-It returns the shallow copy of the given dictionary.This method does not take any parameter.
e.g.
dict1={101:'Ram',102:'Sachin',103:'sita',104:'david'}
dict2=dict1.copy()
print(dict2)
Output:-
{101: 'Ram', 102: 'Sachin', 103: 'sita', 104: 'devid'}
>>>
Difference between copy() and equal(=) operator in dictionary:-
There are some differences in between them.
1.) When we use copy() method with dictionary(dict1). we generate a new copy of dictionary(dict2).When new dictionary(dict2) is cleared then new dictionary(dict2) remains unchanged.dict1={101:'Ram',102:'Sachin',103:'sita',104:'david'}
dict2=dict1.copy()
dict2.clear()
print(dict1)
print(dict2)
dict1={101:'Ram',102:'Sachin',103:'sita',104:'david'}
dict2=dict1
dict2.clear()
print(dict1)
print(dict2)
Output:-- dict1.update(dict2):-It is used to update the one dictionary values from other dictionary values.
dict1={1:'HCL',2:'NOKIA',3:'SUMSANG',4:'Wipro',5:'Microsoft',101:'HP'}
dict2={101:'Ram',102:'Sachin',103:'sita',104:'david'}
dict1.update(dict2)
print(dict1)
Output:-
{1: 'HCL', 2: 'NOKIA', 3: 'SUMSANG', 4: 'Wipro', 5: 'Microsoft', 101: 'Ram', 102: 'Sachin', 103: 'sita', 104: 'david'}
>>>
- dict.items():-It returns all the type-value pair as a tuple.This method does not take any argument.
dict1={101:'Ram',102:'Sachin',103:'sita',104:'david'}
a=dict1.items()
print(a)
Output:-
dict_items([(101, 'Ram'), (102, 'Sachin'), (103, 'sita'), (104, 'david')])
>>>
- dict.keys():-It returns list of all keys in given dictionary.
e.g.
dict1={101:'Ram',102:'Sachin',103:'sita',104:'david'}
a=dict1.keys()
print(a)
Output:-
dict_keys([101, 102, 103, 104])
>>>
- dict.values():-It returns list of all values in given dictionary.
dict1={101:'Ram',102:'Sachin',103:'sita',104:'david'}
a=dict1.values()
print(a)
Output:-
dict_values(['Ram', 'Sachin', 'sita', 'david'])
>>>
Program 1:Write a program to create a dictionary and insert some values by user.
student={}
print(type(student))
print(student)
print("Enter the given student details:")
student["name"]=input("Enter the student name: ")
student["roll_number"]=int(input("Enter the student roll_number: "))
student["age"]=int(input("Enter the student age: "))
student["salary"]=int(input("Enter the student salary: "))
student["company"]=input("Enter the student company name: ")
print("student details is printing...")
print(student)
Output:-
<class 'dict'>
{}
Enter the given student details:
Enter the student name: Ram
Enter the student roll_number: 1201005
Enter the student age: 35
Enter the student salary: 25000
Enter the student company name: MNT LAB
student details is printing...
{'name': 'Ram', 'roll_number': 1201005, 'age': 35, 'salary': 25000, 'company': 'MNT LAB'}
>>>
Watch Complete Lecture 28 Video:
---------------Coming soon----------------
For More...
0 comments:
Post a Comment