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

Python Dictionaries.ppt

The document provides an overview of Python data structures, focusing on lists, tuples, sets, and dictionaries. It explains their characteristics, operations, and methods for adding, updating, and removing elements. Each data structure is described with examples and syntax to illustrate their usage in Python programming.

Uploaded by

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

Python Dictionaries.ppt

The document provides an overview of Python data structures, focusing on lists, tuples, sets, and dictionaries. It explains their characteristics, operations, and methods for adding, updating, and removing elements. Each data structure is described with examples and syntax to illustrate their usage in Python programming.

Uploaded by

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

PYTHON DATA STRUCTURES

Ms P Mhlanga
University of Zimbabwe
Department of Computer Science
LISTS
◻ A list in Python is used to store the sequence of
various types of data. Python lists are mutable type
its mean we can modify its element after it created.
However, Python consists of six data-types that are
capable to store the sequences, but the most
common and reliable type is the list.
◻ A list can be defined as a collection of values or
items of different types. The items in the list are
separated with the comma (,) and enclosed with the
square brackets [].

◻ A list can be define as below
◻ L1 = ["John", 102, "USA"]
◻ L2 = [1, 2, 3, 4, 5, 6]

◻ print(type(L1))
◻ print(type(L2))
Characteristics of lists
◻ The list has the following characteristics:
◻ The lists are ordered.
◻ The element of the list can access by index.
◻ The lists are the mutable type.
◻ The lists are mutable types.
◻ A list can store the number of various elements.
List indexing and splitting

◻ The indexing is processed in the same way as it


happens with the strings. The elements of the list can
be accessed by using the slice operator [].
◻ The index starts from 0 and goes to length - 1. The
first element of the list is stored at the 0th index, the
second element of the list is stored at the 1st index,
and so on.
◻ The start denotes the starting index position of the
list.
◻ The stop denotes the last index position of the list.
◻ The step is used to skip the nth element within a
start:stop
Updating lists
◻ Lists are the most versatile data structures in Python
since they are mutable, and their values can be
updated by using the slice and assignment operator.
◻ Python also provides append() and insert() methods,
which can be used to add values to the list.
Insert()
◻ Syntax: list_name.insert(index, element)
◻ Parameters:
◻ index: the index at which the element has to be inserted.
◻ element: the element to be inserted in the list.
◻ Returns: Does not return any value.

◻ list.(index,object)
◻ Print(list)
Insert() before an element
◻ ist1 = [ 1, 2, 3, 4, 5, 6 ]
◻ # Element to be inserted
◻ element = 13
◻ # Element to be inserted before 3
◻ beforeElement = 3
◻ # Find index
◻ index = list1.index(beforeElement)
◻ # Insert element at beforeElement
◻ list1.insert(index, element)
◻ print(list1)

◻ list = [1, 2, 3, 4, 5, 6]
◻ print(list)
◻ # It will assign value to the value to the second inde
x
◻ list[2] = 10
◻ print(list)
◻ # Adding multiple-element
◻ list[1:3] = [89, 78]
..
◻ print(list)
◻ # It will add value at the end of the list
◻ list[-1] = 25
◻ print(list)

◻ The list elements can also be deleted by using the
del keyword. Python also provides us the remove()
method if we do not know which element is to be
deleted from the list.
Python lists operations
◻ The concatenation (+) and repetition (*) operators
work in the same way as they were working with the
strings.
◻ Let's see how the list responds to various operators.
Iterating a list
◻ list can be iterated by using a for - in loop. A simple
list containing four strings, which can be iterated as
follows.
◻ list = ["John", "David", "James", "Jonathan"]

◻ for i in list:

# The i variable will iterate over the elements of the


List and contains each element in each iteration.
◻ print(i)
Adding elements
◻ Python provides append() function which is used to
add an element to the list. However, the append()
function can only add value to the end of the list.
Removing elements from list
◻ Python provides the remove() function which is used
to remove the element from the list. Consider the
following example to understand this concept.

◻ list = [0,1,2,3,4]
◻ print("printing original list: ");
◻ for i in list:
◻ print(i,end=" ")
◻ list.remove(2)
◻ print("\nprinting the list after the removal of first element...")
◻ for i in list:
◻ print(i,end=" ")
….

◻ Write the program to remove the duplicate element


of the list.
◻ list1 = [1,2,2,3,55,98,65,65,13,29]

◻ 2- Write a program to find the sum of the element


in the list.
..
◻ Write the program to find the lists consist of at least
one common element.
◻ list1 = [1,2,3,4,5,6]
◻ list2 = [7,8,9,2,10]
Tuple
◻ A tuple is a collection of objects which ordered and
immutable. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples
cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets.
◻ Creating a tuple is as simple as putting different
comma-separated values. Optionally you can put
these comma-separated values between
parentheses also. For example
Example
◻ tup1 = ('physics', 'chemistry', 1997, 2000); tup2 =
(1, 2, 3, 4, 5 ); tup3 = "a", "b", "c", "d";

◻ To write a tuple containing a single value you have
to include a comma, even though there is only one
value −
◻ tup1 = (50,);
tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5, 6, 7 ); print "tup1[0]: ", tup1[0]; print "tup2[1:5]: ", tup2[1:5];

Accessing values in tuples


◻ To access values in tuple, use the square brackets for
slicing along with the index or indices to obtain
value available at that index. For example −
◻ tup1 = ('physics', 'chemistry', 1997, 2000);
◻ tup2 = (1, 2, 3, 4, 5, 6, 7 );
◻ print "tup1[0]: ", tup1[0];
◻ print "tup2[1:5]: ", tup2[1:5];
Updating tuples
◻ Tuples are immutable which means you cannot
update or change the values of tuple elements. You
are able to take portions of existing tuples to
create new tuples as the following example
demonstrates
..
◻ tup1 = (12, 34.56);
◻ tup2 = ('abc', 'xyz');
◻ # Following action is not valid for tuples # tup1[0]
= 100; # So let's create a new tuple as follows
tup3 = tup1 + tup2; print tup3;
Deleting a tuple
◻ Removing individual tuple elements is not possible.
There is, of course, nothing wrong with putting
together another tuple with the undesired elements
discarded.
◻ To explicitly remove an entire tuple, just use the del
statement. For example −
◻ tup = ('physics', 'chemistry', 1997, 2000);
◻ print tup;
◻ del tup;
◻ print "After deleting tup : "; print tup;
Tuple operations
◻ Tuples respond to the + and * operators much like
strings; they mean concatenation and repetition here
too, except that the result is a new tuple, not a
string.
Sets in python
◻ Mathematically a set is a collection of items not in
any particular order. A Python set is similar to this
mathematical definition with below additional
conditions.
◻ The elements in the set cannot be duplicates.
◻ The elements in the set are immutable(cannot be
modified) but the set as a whole is mutable.
◻ There is no index attached to any element in a
python set. So they do not support any indexing or
slicing operation.
Set Operations
◻ The sets in python are typically used for
mathematical operations like union, intersection,
difference and complement etc. We can create a
set, access it’s elements and carry out these
mathematical operations as shown below
Creating a set
◻ A set is created by using the set() function or placing
all the elements within a pair of curly braces.
..
◻ Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"
])
◻ Months={"Jan","Feb","Mar"}
◻ Dates={21,22,17}
◻ print(Days)
◻ print(Months)
◻ print(Dates)
Accessing Values in a Set
◻ We cannot access individual values in a set. We can
only access all the elements together as shown
above. But we can also get a list of individual
elements by looping through the set.
◻ Example
◻ Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"
])
◻ for d in Days:
◻ print(d)
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"]) Days.add("Sun") print(Days)

Adding items to the set


◻ We can add elements to a set by using add()
method. Again as discussed there is no specific
index attached to the newly added element.
Example
◻ Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.add("Sun")
◻ print(Days)
Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"]) Days.discard("Sun") print(Days)

Removing item from the set


◻ We can remove elements from a set by using
discard() method.
◻ Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])
Days.discard("Sun")
◻ print(Days)
The union operation on two sets produces a new set containing all the distinct elements from both
the sets. In the below example the element “Wed” is present in both the sets.
Example
DaysA = set(["Mon","Tue","Wed"]) DaysB = set(["Wed","Thu","Fri","Sat","Sun"]) AllDays = DaysA|DaysB print(AllDays)

Union of sets
◻ The union operation on two sets produces a new set
containing all the distinct elements from both the
sets. In the below example the element “Wed” is
present in both the sets.
◻ Example
◻ DaysA = set(["Mon","Tue","Wed"])
◻ DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
◻ AllDays = DaysA|DaysB
◻ print(AllDays)
Intersection of sets
◻ Intersection of Sets
◻ The intersection operation on two sets produces a
new set containing only the common elements from
both the sets. In the below example the element
“Wed” is present in both the sets.
◻ DaysA = set(["Mon","Tue","Wed"])
◻ DaysB = set(["Wed","Thu","Fri","Sat","Sun"])
◻ AllDays = DaysA & DaysB
◻ print(AllDays)
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 a 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.

◻ In the above dictionary Dict, The keys Name and Age


are the string that is an immutable object.
Example to create a dictionary and
print its content.

◻ 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
Output
Accessing Dictionaries

◻ We have discussed how the data can be accessed in the


list and tuple 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.
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. The
update() method is also used to update an existing
value.
◻ Note: If the key-value already present in the
dictionary, the value gets updated. Otherwise, the new
keys added in the dictionary.
Example
Deleting elements using del keyword

◻ The items of the dictionary can be deleted by using


the del keyword as given below.
Output

◻ The last print statement in the above code, it raised an


error because we tried to print the Employee
dictionary that already deleted.
Pop method()
◻ The pop() method accepts the key as an argument and
remove the associated value. Consider the following
example

◻ Python also provides a built-in methods popitem() and


clear() method for remove elements from the
dictionary. The popitem() removes the arbitrary
element from a dictionary, whereas the clear() method
removes all elements to the whole dictionary.
Iterating Dictionary

◻ A dictionary can be iterated using for loop as given


below.
Properties of Dictionary keys

■ In the dictionary, we cannot store multiple values for the


same keys. If we pass more than one value for a single
key, then the value which is last assigned is considered
as the value of the key.
■ Consider the following example.
Notes

■ In python, the key cannot be any mutable object. We


can use numbers, strings, or tuples as the key, but we
cannot use any mutable object like the list as the key
in the dictionary.
Built-in Dictionary functions
….
Built-in Dictionary methods
THANK YOU

You might also like