Unit-2 Lect 3
Unit-2 Lect 3
Python Dictionary
Python Dictionary is used to store the data in a key-value
pair format. The dictionary is the data type in Python,
which can simulate the real-life data arrangement where
some specific value exists for some particular key.
It is the mutable data-structure.
The dictionary is defined into element Keys and values.
Keys must be a single element
Value can be any type such as list, tuple, integer, etc.
In other words, we can say that a dictionary is the collection
of key-value pairs where the value can be any Python
object. In contrast, the keys are the immutable Python
object, i.e., Numbers, string, or tuple.
Creating the dictionary
The dictionary can be created by using multiple key-value
pairs enclosed with the curly brackets {}, and each key is
separated from its value by the colon (:).
The syntax to define the dictionary is given below.
Dict = {"Name": "Tom", "Age": 22}
In the above dictionary Dict, The keys Name and Age are the
string that is an immutable object.
Let's see an example to create a dictionary and print its
content.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Compan
y":"GOOGLE"}
print(type(Employee))
print("printing Employee data .... ")
print(Employee)
Python provides the built-in function dict() method
which is also used to create dictionary. The empty
curly braces {} is used to create empty dictionary.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict) # {}
# Creating a Dictionary
# with dict() method
Dict = dict({1: ‘python', 2: ‘high', 3:'Point'})
print("\nCreate Dictionary by using dict(): ")
print(Dict) # {1: ‘python', 2: ‘high', 3:'Point'}
Accessing the dictionary values
We have discussed how the data can be accessed in the list
and string by using the indexing.
However, the values can be accessed in the dictionary by
using the keys as keys are unique in the dictionary.
The dictionary values can be accessed in the following way.
Employee = {"Name": "John", "Age": 29}
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
Output:
printing Employee data ....
Name : John
Age : 29
Adding dictionary values
The dictionary is a mutable data type, and its values can be updated by
using the specific keys.
The value can be updated along with key Dict[key] = value.
Note: If the key-value already present in the dictionary, the value
gets updated. Otherwise, the new keys added in the dictionary.
Let's see an example to update the dictionary values.
# Creating an empty Dictionary
D = {}
# Adding elements to dictionary one at a time
D[0] = 'Peter'
D[7] = 'Joseph'
D[90] = 'Ricky'
print("\nDictionary after adding 3 elements: ")
print(Dict)
Output:
Dictionary after adding 3 elements:
{0: 'Peter', 7: 'Joseph', 90: 'Ricky'}
print(D[1])
Deleting elements using del keyword
The items of the dictionary can be deleted by using
the del keyword as given below.
Employee = {"Name": "John", "Age": 29, "salary":25000,"Comp
any":"GOOGLE"}
print("Deleting some of the employee data")
del Employee["Name"]
del Employee["Company"]
print("printing the modified information ")
print(Employee)
print("Deleting the dictionary: Employee");
del Employee
print("Lets try to print it again ");
print(Employee)
Output:
Deleting some of the employee data
printing the modified information
{'Age': 29, 'salary': 25000}
Deleting the dictionary: Employee
Lets try to print it again
Traceback (most recent call last):
File "<string>", line 11, in <module>
NameError: name 'Employee' is not defined
Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example 1
# for loop to print all the keys of a dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"Comp
any":"GOOGLE"}
for x in Employee:
print(x)
Output:
Name
Age
salary
Company
Example 2
#for loop to print all the values of the dictionary
Employee = {"Name": "John", "Age": 29, "salary":25000,"C
ompany":"GOOGLE"}
for x in Employee:
print(Employee[x])
Output:
John
29
25000
GOOGLE
Example - 3
#for loop to print the values of the dictionary by
using values() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"C
ompany":"GOOGLE"}
for x in Employee.values():
print(x)
Output:
John
29
25000
GOOGLE
Example 4
#for loop to print the items of the dictionary by
using items() method.
Employee = {"Name": "John", "Age": 29, "salary":25000,"C
ompany":"GOOGLE"}
for x in Employee.items():
print(x)
Output:
('Name', 'John')
('Age', 29)
('salary', 25000)
('Company', 'GOOGLE')
S. No Function Description
1 dic.clear() It is used to delete all the items of the dictionary.
2 dict.has_key(key) It returns true if the dictionary contains the
specified key.
3 dict.items() It returns all the key-value pairs as a tuple.
4 dict.keys() It returns all the keys of the dictionary.
5 dict.update(dict2) It updates the dictionary by adding the key-value
pair of dict2 to this dictionary.
6 dict.values() It returns all the values of the dictionary.
7 len() It returns length of the dictionary.
8 popItem() method removes the item that was last inserted
into the dictionary
9 pop() method removes the item using key from the
dictionary
Dictionary Methods:
Len
Str
Clear
Copy
Get
Update
len method:
Python dictionary method len() gives the total length
of the dictionary. This would be equal to the number
of items in the dictionary.
Syntax
Following is the syntax for len() method −
len(dict)
dict − This is the dictionary, whose length needs to be
calculated.
Example:
dict = {'Name': 'Zara', 'Age': 7}
print "Length : %d" % len (dict)
OUTPUT:
Length : 2
str method
Python dictionary method str() produces a printable
string representation of a dictionary.
Syntax
Following is the syntax for str() method −
str(dict)
dict − This is the dictionary.
Example:
dict = {'Name': 'Manni', 'Age': 7, 'Class': 'First'}
print ("Equivalent String : %s" % str (dict))
Output:
Equivalent String : {'Name': 'Manni', 'Age': 7, 'Class':
'First'}
clear method
The clear() method removes all items from the dictionary.
Example:
# dictionary
numbers = {1: "one", 2: "two"}
print(numbers)
# Output: {}
copy method
The copy() method returns a copy of the dictionary.
Example:
original_marks = {'Physics':67, 'Maths':87}
copied_marks = original_marks.copy()
Output:
Original Marks: {'Physics': 67, 'Maths': 87}
Copied Marks: {'Physics': 67, 'Maths': 87}
get method
The get() method returns the value for the specified
key if the key is in the dictionary.
Example:
marks = {'Physics':67, 'Maths':87}
print(marks.get('Physics'))
# Output: 67
update method
The update() method updates the dictionary with the
elements from another dictionary object or from an
iterable of key/value pairs.
Example:
marks = {'Physics':67, 'Maths':87}
internal_marks = {'Practical':48}
marks.update(internal_marks)
print(marks)
Output:
{'Physics': 67, 'Maths': 87, 'Practical': 48}
Example:2
d = {1: "one", 2: "three"}
d1 = {2: "two"}
# updates the value of key 2
d.update(d1)
print(d)
d1 = {3: "three"}
# adds element with key 3
d.update(d1)
print(d)
OUTPUT:
{1: 'one', 2: 'two'}
{1: 'one', 2: 'two', 3: 'three'}
Example 3: update() When Tuple is
Passed
dictionary = {'x': 2}
dictionary.update([('y', 3), ('z', 0)])
print(dictionary)
OUTPUT:
{'x': 2, 'y': 3, 'z': 0}
NOTE:
Here, we have passed a list of tuples [('y', 3), ('z', 0)] to
the update() function.
In this case, the first element of tuple is used as the key
and the second element is used as the value.
keys method
The keys() method extracts the keys of the dictionary and
returns the list of keys as a view object.
Example:
numbers = {1: 'one', 2: 'two', 3: 'three'}
print(dictionaryKeys)
print(marks.values())