0% found this document useful (0 votes)
3 views

Python Update module 4

Uploaded by

Farzana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Update module 4

Uploaded by

Farzana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Web Development with Python and Django

Python Collections
A collection is similar to a basket that you can add and remove items from. In some cases, they are the same types of
items, and in others they are different. Basically, it's a storage construct that allows you to collect things.

Python offers several built-in types that fall under a vague category called collections. While there isn't a formal type
called collection in Python, there are lists, Tuples, mappings, and sets.

List
Lists in Python are a built-in type called a sequence. List are mutable and allow you to add items of the same
type or different types, making them very versatile constructs. Python lists are similar to arrays in other
languages.

Python lists do allow you to have non-unique elements.


In Python programming, a list is created by placing all the items (elements) inside a square bracket [ ],
separated by commas.

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
It can have any number of items and they may be of different types (integer, float, string etc.).

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes


my_list = [1, "Hello", 3.4]

Also, a list can even have another list as an item. This is called nested list.

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

List Index

We can use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5 elements
will have index from 0 to 4.

Trying to access an element other that this will raise an IndexError. The index must be an integer. We can't
use float or other types, this will result into TypeError.

Nested list are accessed using nested indexing.

my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])

# Output: o
print(my_list[2])

# Output: e
print(my_list[4])

# Error! Only integer can be used for indexing


# my_list[4.0]

# Nested List
n_list = ["Happy", [2,0,1,5]]

# Nested indexing

# Output: a
print(n_list[0][1])

# Output: 5
print(n_list[1][3])

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
Negative indexing

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last
item and so on.

my_list = ['p','r','o','b','e']

# Output: e
print(my_list[-1])

# Output: p
print(my_list[-5])

How to slice lists in Python?


We can access a range of items in a list by using the slicing operator (colon).

my_list = ['p','r','o','g','r','a','m','i','z']
# elements 3rd to 5th
print(my_list[2:5])

# elements beginning to 4th


print(my_list[:-5])

# elements 6th to end


print(my_list[5:])

# elements beginning to end


print(my_list[:])

Slicing can be best visualized by considering the index to be between the elements as shown below. So if we want to
access a range, we need two index that will slice that portion from the list.

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
How to change or add elements to a list?
List are mutable, meaning, their elements can be changed.
We can use assignment operator (=) to change an item or a range of items.

# mistake values
odd = [2, 4, 6, 8]

# change the 1st item


odd[0] = 1

# Output: [1, 4, 6, 8]
print(odd)

# change 2nd to 4th items


odd[1:4] = [3, 5, 7]

# Output: [1, 3, 5, 7]
print(odd)

We can add one item to a list using append() method or add several items using extend() method.

odd = [1, 3, 5]

odd.append(7)

# Output: [1, 3, 5, 7]
print(odd)

odd.extend([9, 11, 13])

# Output: [1, 3, 5, 7, 9, 11, 13]


print(odd)

How to delete or remove elements from a list?


We can delete one or more items from a list using the keyword del. It can even delete the list entirely.

my_list = ['p','r','o','b','l','e','m']

# delete one item


del my_list[2]

# Output: ['p', 'r', 'b', 'l', 'e', 'm']


print(my_list)

# delete multiple items


del my_list[1:5]
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
# Output: ['p', 'm']
print(my_list)

# delete entire list


del my_list

# Error: List not defined


print(my_list)

We can use remove() method to remove the given item or pop() method to remove an item at the given
index.

The pop() method removes and returns the last item if index is not provided. This helps us implement lists as
stacks (first in, last out data structure).

We can also use the clear() method to empty a list.

my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')

# Output: ['r', 'o', 'b', 'l', 'e', 'm']


print(my_list)

# Output: 'o'
print(my_list.pop(1))

# Output: ['r', 'b', 'l', 'e', 'm']


print(my_list)

# Output: 'm'
print(my_list.pop())

# Output: ['r', 'b', 'l', 'e']


print(my_list)

my_list.clear()

# Output: []
print(my_list)

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
Some examples of Python list methods:
my_list = [3, 8, 1, 6, 0, 8, 4]

# Output: 1
print(my_list.index(8))

# Output: 2
print(my_list.count(8))

my_list.sort()

# Output: [0, 1, 3, 4, 6, 8, 8]
print(my_list)

my_list.reverse()

# Output: [8, 8, 6, 4, 3, 1, 0]
print(my_list)

Python Tuple
What is tuple?
In Python programming, a tuple is similar to a list. The difference between the two is that we cannot change
the elements of a tuple once it is assigned whereas in a list, elements can be changed.

Advantages of Tuple over List

Since, tuples are quite similiar to lists, both of them are used in similar situations as well.

However, there are certain advantages of implementing a tuple over a list. Below listed are some of the main
advantages:

 We generally use tuple for heterogeneous (different) datatypes and list for homogeneous (similar)
datatypes.
 Since tuple are immutable, iterating through tuple is faster than with list. So there is a slight
performance boost.
 Tuples that contain immutable elements can be used as key for a dictionary. With list, this is not
possible.
 If you have data that doesn't change, implementing it as tuple will guarantee that it remains write-
protected.

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
Creating a Tuple
A tuple is created by placing all the items (elements) inside a parentheses (), separated by comma. The
parentheses are optional but is a good practice to write it.

A tuple can have any number of items and they may be of different types (integer, float, list, string etc.).

# empty tuple

# Output: ()

my_tuple = ()

print(my_tuple)

# tuple having integers

# Output: (1, 2, 3)

my_tuple = (1, 2, 3)

print(my_tuple)

# tuple with mixed datatypes

# Output: (1, "Hello", 3.4)

my_tuple = (1, "Hello", 3.4)

print(my_tuple)

# nested tuple

# Output: ("mouse", [8, 4, 6], (1, 2, 3))

my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

print(my_tuple)

# tuple can be created without parentheses

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
# also called tuple packing

# Output: 3, 4.6, "dog"

my_tuple = 3, 4.6, "dog"

print(my_tuple)

# tuple unpacking is also possible

# Output:

#3

# 4.6

# dog

a, b, c = my_tuple

print(a)

print(b)

print(c)

Accessing Elements in a Tuple


There are various ways in which we can access the elements of a tuple.

1. Indexing

We can use the index operator [] to access an item in a tuple where the index starts from 0.
So, a tuple having 6 elements will have index from 0 to 5. Trying to access an element other that (6, 7,...)
will raise an IndexError.

The index must be an integer, so we cannot use float or other types. This will result into TypeError.
Likewise, nested tuple are accessed using nested indexing, as shown in the example below.

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
my_tuple = ('p','e','r','m','i','t')

# Output: 'p'

print(my_tuple[0])

# Output: 't'

print(my_tuple[5])

# index must be in range

# If you uncomment line 14,

# you will get an error.

# IndexError: list index out of range

#print(my_tuple[6])

# index must be an integer

# If you uncomment line 21,

# you will get an error.

# TypeError: list indices must be integers, not float

#my_tuple[2.0]

# nested tuple

n_tuple = ("mouse", [8, 4, 6], (1, 2, 3))

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
# nested index

# Output: 's'

print(n_tuple[0][3])

# nested index

# Output: 4

print(n_tuple[1][1])

When you run the program, the output will be:

p
t
s
4

Negative Indexing

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on.

my_tuple = ('p','e','r','m','i','t')

# Output: 't'

print(my_tuple[-1])

# Output: 'p'

print(my_tuple[-6])

Slicing

We can access a range of items in a tuple by using the slicing operator - colon ":".

my_tuple = ('p','r','o','g','r','a','m','i','z')

# elements 2nd to 4th

# Output: ('r', 'o', 'g')

print(my_tuple[1:4])
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
# elements beginning to 2nd

# Output: ('p', 'r')

print(my_tuple[:-7])

# elements 8th to end

# Output: ('i', 'z')

print(my_tuple[7:])

# elements beginning to end

# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

print(my_tuple[:])

Changing a Tuple
Unlike lists, tuples are immutable.

This means that elements of a tuple cannot be changed once it has been assigned. But, if the element is itself
a mutable datatype like list, its nested items can be changed.

We can also assign a tuple to different values (reassignment).

my_tuple = (4, 2, 3, [6, 5])

# we cannot change an element

# If you uncomment line 8

# you will get an error:

# TypeError: 'tuple' object does not support item assignment

#my_tuple[1] = 9

# but item of mutable element can be changed

# Output: (4, 2, 3, [9, 5])

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
my_tuple[3][0] = 9

print(my_tuple)

# tuples can be reassigned

# Output: ('p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z')

my_tuple = ('p','r','o','g','r','a','m','i','z')

print(my_tuple)

We can use + operator to combine two tuples. This is also called concatenation.

We can also repeat the elements in a tuple for a given number of times using the * operator.

Both + and * operations result into a new tuple.

# Concatenation

# Output: (1, 2, 3, 4, 5, 6)

print((1, 2, 3) + (4, 5, 6))

# Repeat

# Output: ('Repeat', 'Repeat', 'Repeat')

print(("Repeat",) * 3)

Deleting a Tuple
As discussed above, we cannot change the elements in a tuple. That also means we cannot delete or remove
items from a tuple.

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
But deleting a tuple entirely is possible using the keyword del.

my_tuple = ('p','r','o','g','r','a','m','i','z')

# can't delete items

# if you uncomment line 8,

# you will get an error:

# TypeError: 'tuple' object doesn't support item deletion

#del my_tuple[3]

# can delete entire tuple

# NameError: name 'my_tuple' is not defined

del my_tuple

my_tuple

Python Tuple Methods


Methods that add items or remove items are not available with tuple. Only the following two methods are
available.

my_tuple = ('a','p','p','l','e',)

# Count

# Output: 2

print(my_tuple.count('p'))

# Index

# Output: 3

print(my_tuple.index('l'))

Python Strings
What is String in Python?

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
A string is a sequence of characters.

A character is simply a symbol. For example, the English language has 26 characters.

Computers do not deal with characters, they deal with numbers (binary). Even though you may see
characters on your screen, internally it is stored and manipulated as a combination of 0's and 1's.

This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and
Unicode are some of the popular encoding used.

How to create a string in Python?


Strings can be created by enclosing characters inside a single quote or double quotes. Even triple quotes can
be used in Python but generally used to represent multiline strings and docstrings.

# all of the following are equivalent

my_string = 'Hello'

print(my_string)

my_string = "Hello"

print(my_string)

my_string = '''Hello'''

print(my_string)

# triple quotes string can extend multiple lines

my_string = """Hello, welcome to

the world of Python"""

print(my_string)

When you run the program, the output will be:

Hello
Hello
Hello
Hello, welcome to
the world of Python

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
How to access characters in a string?
We can access individual characters using indexing and a range of characters using slicing. Index starts from
0. Trying to access a character out of index range will raise an IndexError. The index must be an integer.
We can't use float or other types, this will result into TypeError.

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 to the second last item and so on. We can access a range of items in
a string by using the slicing operator (colon).

str = 'programiz'
print('str = ', str)

#first character
print('str[0] = ', str[0])

#last character
print('str[-1] = ', str[-1])

#slicing 2nd to 5th character


print('str[1:5] = ', str[1:5])

#slicing 6th to 2nd last character


print('str[5:-2] = ', str[5:-2])

Iterating Through String

Using for loop we can iterate through a string. Here is an example to count the number of 'l' in a string.

count = 0
for letter in 'Hello World':
if(letter == 'l'):
count += 1
print(count,'letters found')

Built-in functions to Work with Python

Various built-in functions that work with sequence, works with string as well.

Some of the commonly used ones are enumerate() and len(). The enumerate() function returns an
enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful for
iteration.
Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
Similarly, len() returns the length (number of characters) of the string.

str = 'cold'

# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)

#character count
print('len(str) = ', len(str))

Python Sets
What is a set in Python?

A set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable
(which cannot be changed).

However, the set itself is mutable. We can add or remove items from it.

Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc.

How to create a set?

A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by using the
built-in function set().

It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set
cannot have a mutable element, like list, set or dictionary, as its element.

# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes


my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
# set do not have duplicates
# Output: {1, 2, 3, 4}
my_set = {1,2,3,4,3,2}
print(my_set)

# set cannot have mutable items


# here [3, 4] is a mutable list
# If you uncomment line #12,
# this will cause an error.
# TypeError: unhashable type: 'list'

#my_set = {1, 2, [3, 4]}

# we can make set from a list


# Output: {1, 2, 3}
my_set = set([1,2,3,2])
print(my_set)

How to change a set in Python?


Sets are mutable. But since they are unordered, indexing have no meaning.

We cannot access or change an element of set using indexing or slicing. Set does not support it.

We can add single element using the add() method and multiple elements using the update() method. The
update() method can take tuples, lists, strings or other sets as its argument. In all cases, duplicates are
avoided.

# initialize my_set
my_set = {1,3}
print(my_set)

# if you uncomment line 9,


# you will get an error
# TypeError: 'set' object does not support indexing

#my_set[0]

# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)

# add multiple elements


# Output: {1, 2, 3, 4}
my_set.update([2,3,4])

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
print(my_set)

# add list and set


# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4,5], {1,6,8})
print(my_set)

When you run the program, the output will be:

{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 8}

A particular item can be removed from set using methods, discard() and remove().

The only difference between the two is that, while using discard() if the item does not exist in the set, it
remains unchanged. But remove() will raise an error in such condition.

The following example will illustrate this.

# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)

# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)

# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)

# discard an element
# not present in my_set
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)

# remove an element
# not present in my_set
# If you uncomment line 27,
# you will get an error.
# Output: KeyError: 2

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
#my_set.remove(2)

Similarly, we can remove and return an item using the pop() method.

Set being unordered, there is no way of determining which item will be popped. It is completely arbitrary.

We can also remove all items from a set using clear().

# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)

# pop an element
# Output: random element
print(my_set.pop())

# pop another element


# Output: random element
my_set.pop()
print(my_set)

# clear my_set
#Output: set()
my_set.clear()
print(my_set)

Python Dictionary

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
What is dictionary in Python?

Python dictionary is an unordered collection of items. While other compound data types have only value as
an element, a dictionary has a key: value pair.

Dictionaries are optimized to retrieve values when the key is known.

How to create a dictionary?

Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.

An item has a key and the corresponding value expressed as a pair, key: value.

While values can be of any data type and can repeat, keys must be of immutable type (string, number or
tuple with immutable elements) and must be unique.

# empty dictionary
my_dict = {}

# dictionary with integer keys


my_dict = {1: 'apple', 2: 'ball'}

# dictionary with mixed keys


my_dict = {'name': 'John', 1: [2, 4, 3]}

# using dict()
my_dict = dict({1:'apple', 2:'ball'})

# from sequence having each item as a pair


my_dict = dict([(1,'apple'), (2,'ball')])

How to access elements from a dictionary?

While indexing is used with other container types to access values, dictionary uses keys. Key can be used
either inside square brackets or with the get() method.

The difference while using get() is that it returns None instead of KeyError, if the key is not found.

my_dict = {'name':'Jack', 'age': 26}

# Output: Jack

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
print(my_dict['name'])

# Output: 26
print(my_dict.get('age'))

# Trying to access keys which doesn't exist throws error


# my_dict.get('address')
# my_dict['address']

When you run the program, the output will be:

Jack
26

How to change or add elements in a dictionary?

Dictionary are mutable. We can add new items or change the value of existing items using assignment
operator.

If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.

my_dict = {'name':'Jack', 'age': 26}

# update value
my_dict['age'] = 27

#Output: {'age': 27, 'name': 'Jack'}


print(my_dict)

# add item
my_dict['address'] = 'Downtown'

# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}


print(my_dict)

When you run the program, the output will be:

{'name': 'Jack', 'age': 27}


{'name': 'Jack', 'age': 27, 'address': 'Downtown'}

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
How to delete or remove elements from a dictionary?

We can remove a particular item in a dictionary by using the method pop(). This method removes as item
with the provided key and returns the value.

The method, popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary.
All the items can be removed at once using the clear() method.

We can also use the del keyword to remove individual items or the entire dictionary itself.

# create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25}

# remove a particular item


# Output: 16
print(squares.pop(4))

# Output: {1: 1, 2: 4, 3: 9, 5: 25}


print(squares)

# remove an arbitrary item


# Output: (1, 1)
print(squares.popitem())

# Output: {2: 4, 3: 9, 5: 25}


print(squares)

# delete a particular item


del squares[5]

# Output: {2: 4, 3: 9}
print(squares)

# remove all items


squares.clear()

# Output: {}
print(squares)

# delete the dictionary itself


del squares

# Throws Error
# print(squares)

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.
When you run the program, the output will be:

16
{1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9}
{}

Designed by Abdur Rahman Joy - MCSD, MCPC, MCSE, MCTS, OCJP, Sr. Technical Trainer for C#.net, JAVA,
Android/IOS/Windows Mobile Apps, SQL server, Azure, Oracle, SharePoint Development, AWS , CEH, KALI Linux,
Python, Software Testing, Graphics, Multimedia and Game Developer at Joy Infosys, Cell #: +880-1712587348,
email: [email protected]. Web URL: http://www.joyinfosys.com/me.

You might also like