[go: up one dir, main page]

0% found this document useful (0 votes)
24 views43 pages

Unit-2 Lect 3

The document provides an overview of Python dictionaries, detailing their structure as key-value pairs, creation methods, and various operations such as accessing, adding, deleting, and iterating through elements. It also covers built-in dictionary methods like len(), str(), clear(), and update(), along with examples for each. Additionally, it briefly compares dictionaries with lists in Python.

Uploaded by

srishtiarora0110
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views43 pages

Unit-2 Lect 3

The document provides an overview of Python dictionaries, detailing their structure as key-value pairs, creation methods, and various operations such as accessing, adding, deleting, and iterating through elements. It also covers built-in dictionary methods like len(), str(), clear(), and update(), along with examples for each. Additionally, it briefly compares dictionaries with lists in Python.

Uploaded by

srishtiarora0110
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Python Dictionary

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

# removes all the items from the dictionary


numbers.clear()

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

print('Original Marks:', original_marks)


print('Copied Marks:', copied_marks)

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'}

# extracts the keys of the dictionary


dictionaryKeys = numbers.keys()

print(dictionaryKeys)

# Output: dict_keys([1, 2, 3])


values method
The values() method returns a view object that
displays a list of all the values in the dictionary.
Example:
marks = {'Physics':57, 'Maths':77}

print(marks.values())

Output: dict_values([57, 77])


 Concatenation function does work with dictionary.
Merging doesn’t work with dictionary.
Searching in Dictionary :
Comparison doesn’t work in dictionary:
Maximum in Dictionary
Minimum in Dictionary
Sorted in dictionary
Sorted function returns list of keys
 Sum in dictionary
 Return sum of all keys if keys are numbers
Reversed function in dictionary
It can be used for reversing dict/keys/values
 popitem() : It removes and returns item in LIFO order.

 pop(): removes key and returns its values


Nested Dictionaries
Unpacking of Dictionaries
fromkeys()
 A dictionary containing different keys but same values
can be created using a fromkeys()
Difference between List
and Dictionary
What is a List in Python?
 A list is just like an array, but its declaration occurs in
other languages. The lists don’t always need to be
homogenous. Thus, it becomes the most powerful tool
in the case of the Python language. A single list may
consist of various DataTypes, such as Strings, Integers,
and also Objects. The Lists are always mutable. Thus,
we can alter it even after we create it.
What is a Dictionary in Python?
 A dictionary, on the other hand, refers to an unordered
collection of the data values that we use for storing the
data values, such as a map. Unlike the other
DataTypes, which are capable of holding only a single
value in the form of an element, a Dictionary is
capable of holding the key:value pair. In a Dictionary, a
colon separates all the key-value pairs from each other,
while a comma separates all the keys from each other.
Difference Between List and
Dictionary in Python

You might also like