0% found this document useful (0 votes)
2 views17 pages

I BSC Unit IV Python Notes

Uploaded by

rcwcsdept
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)
2 views17 pages

I BSC Unit IV Python Notes

Uploaded by

rcwcsdept
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

III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.

:1

PYTHON PROGRAMMING
UNIT IV
Lists: Creating a list -Access values in List-Updating values in Lists-Nested lists -Basic list
operations-List Methods. Tuples: Creating, Accessing, Updating and Deleting Elements in a tuple
– Nested tuples– Difference between lists and tuples. Dictionaries: Creating, Accessing, Updating
and Deleting Elements in a Dictionary – Dictionary Functions and Methods - Difference between
Lists and Dictionaries.
LISTS
Python Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and
ArrayList in Java). In simple language, a list is a collection of things, enclosed in [ ] and separated by
commas. The list is a sequence data type which is used to store the collection of
data. Tuples and String are other types of sequence data types.

Example of list in Python


Here we are creating Python List using [].
Var = ["Geeks", "for", "Geeks"]
print(Var)
Output:["Geeks", "for", "Geeks"]

Creating a List in Python


Lists in Python can be created by just placing the sequence inside the square brackets[]. Unlike Sets, a
list doesn’t need a built-in function for its creation of a list.
Note: Unlike Sets, the list may contain mutable elements.

Example 1: Creating a list in Python

# Creating a List
List = [] Output
print("Blank List: ")
print(List) Blank List:
# Creating a List of numbers []
List = [10, 20, 14]
print("\nList of numbers: ")
print(List) List of numbers:

# Creating a List of strings and accessing [10, 20, 14]


# using index
List Items:
List = ["Python", "Programming", "Language"]
print("\nList Items: ") Python
print(List[0])
print(List[2]) Programming
Complexities for Creating Lists
Time Complexity: O(1)
Space Complexity: O(n)

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS


III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:2

Example 2: Creating a list with multiple distinct or duplicate elements


A list may contain duplicate values with their distinct positions and hence, multiple distinct or
duplicate values can be passed as a sequence at the time of list creation.
List = [1, 2, 4, 4, 3, 3, 3, 6, 5] Output
print("\nList with the use of Numbers: ") List with the use of Numbers:
print(List) [1, 2, 4, 4, 3, 3, 3, 6, 5]
List = [1, 2, 'Peter', 4, 'For', 6, 'Peter'] List with the use of Mixed Values:
print("\nList with the use of Mixed Values: ") [1, 2, 'Peter', 4, 'For', 6, 'Peter']
print(List)

Accessing elements from the List


In order to access the list items refer to the index number. Use the index operator [ ] to access an item
in a list. The index must be an integer. Nested lists are accessed using nested indexing.
Example 1: Accessing elements from list Output
List = ["Python", "Programming", "Lanaguage"] Accessing a element from the list
print("Accessing a element from the list") Python
print(List[0]) Programming
print(List[2])
Updating List Values
Due to their mutability and the slice and assignment operator's ability to update their values, lists
are Python's most adaptable data structure. Python's append() and insert() methods can also add
values to a list.
Code
list = [1, 2, 3, 4, 5, 6]
print(list)
list[2] = 10
print(list)
list[1:3] = [89, 78]
print(list)
list[-1] = 25
print(list)
Output:
[1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]

Delete using del keyword


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.
Code
Output:
list = [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
print(list) [1, 2, 10, 4, 5, 6]
list[2] = 10 [1, 89, 78, 4, 5, 6]
print(list) [1, 89, 78, 4, 5, 25]
list[1:3] = [89, 78]

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS


III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:3

print(list)
list[-1] = 25
print(list)
Python List Operations
The concatenation (+) and repetition (*) operators work in the same way as they were working with
the strings. The different operations of list are
1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership
Let's see how the list responds to various operators.
1. Repetition
The redundancy administrator empowers the rundown components to be rehashed on different
occasions.
Code
list1 = [12, 14, 16, 18, 20] Output:
l = list1 * 2 [12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
print(l)
2. Concatenation
It concatenates the list mentioned on either side of the operator.
Code
list1 = [12, 14, 16, 18, 20] Output:
list2 = [9, 10, 32, 54, 86] [12, 14, 16, 18, 20, 9, 10, 32, 54, 86]
l = list1 + list2
print(l)
3. Length
It is used to get the length of the list
Code Output:
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40] 9
len(list1)
4. Iteration
The for loop is used to iterate over the list elements.
Output:
Code 12
list1 = [12, 14, 16, 39, 40] 14
for i in list1: 16
39
print(i) 40
5. Membership
It returns true if a particular item exists in a particular list otherwise false.
Code
list1 = [100, 200, 300, 400, 500]
print(600 in list1)
print(700 in list1)

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS


III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:4

print(1040 in list1)
print(300 in list1)
print(100 in list1)
print(500 in list1)
Output:
False
False
False
True
True
True

Nested List or Iterating a List


A list can be iterated by using a for - in loop. A simple list containing four strings, which can be
iterated as follows.
Code
list = ["John", "David", "James", "Jonathan"]
for i in list:
print(i)
Output:
John
David
James
Jonathan

Adding Elements to the List


The append() function in Python can add a new item to the List. In any case, the annex() capability
can enhance the finish of the rundown.
Consider the accompanying model, where we take the components of the rundown from the client
and print the rundown on the control center.
Code
l =[ ]
n = int(input("Enter the number of elements in the list:"))
for i in range(0,n):
[Link](input("Enter the item:"))
print("printing the list items..")
for i in l:
print(i, end = " ")
Output:
Enter the number of elements in the list:10
Enter the item:32
Enter the item:56
Enter the item:81
Enter the item:2
Enter the item:34
Enter the item:65
Enter the item:09
Enter the item:66
Enter the item:12
Enter the item:18
printing the list items..
32 56 81 2 34 65 09 66 12 18

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS


III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:5

Removing Elements from the List


The remove() function in Python can remove an element from the List. To comprehend this idea,
look at the example that follows.
Example -
Code
list = [0,1,2,3,4]
print("printing original list: ");
for i in list:
print(i,end=" ")
[Link](2)
print("\nprinting the list after the removal of first element...")
for i in list:
print(i,end=" ")
Output:
printing original list:
0 1 2 3 4
printing the list after the removal of first element...
0 1 3 4

Python List Built-in Functions


Python provides the following built-in functions, which can be used with the lists.
1. len()
2. max()
3. min()
len( )
It is used to calculate the length of the list.
Code
list1 = [12, 16, 18, 20, 39, 40]
len(list1)
Output:
6
Max( )
It returns the maximum element of the list
Code
list1 = [103, 675, 321, 782, 200]
print(max(list1))
Output:
782
Min( )
It returns the minimum element of the list
Code
list1 = [103, 675, 321, 782, 200]
print(min(list1))
Output:
103
Let's have a look at the few list examples.

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS


III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:6

Example: 1- Create a program to eliminate the List's duplicate items.


Code
list1 = [1,2,2,3,55,98,65,65,13,29]
list2 = [ ]
for i in list1:
if i not in list2:
[Link](i)
print(list2)
Output:
[1, 2, 3, 55, 98, 65, 13, 29]
Example:2- Compose a program to track down the amount of the component in the rundown.
Code
list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)
Output:
The sum is: 67
In [8]:
Example: 3- Compose the program to find the rundowns comprise of somewhere around one
normal component.
Code
list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)
Output:
The common element is: 2
Python Tuples
A Python Tuple is a group of items that are separated by commas. The indexing, nested objects, and
repetitions of a tuple are somewhat like those of a list, however unlike a list, a tuple is immutable. The
distinction between the two is that while we can edit the contents of a list, we cannot alter the elements of a
tuple once they have been assigned.
Example
("Suzuki", "Audi", "BMW"," Skoda ") is a tuple.
Features of Python Tuple
o Tuples are an immutable data type, which means that once they have been generated, their elements cannot be
changed.
o Since tuples are ordered sequences, each element has a specific order that will never change.
Creating of Tuple:
To create a tuple, all the objects (or "elements") must be enclosed in parenthesis (), each one separated by a
comma. Although it is not necessary to include parentheses, doing so is advised.

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS


III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:7

A tuple can contain any number of items, including ones with different data types (dictionary, string, float,
list, etc.).
Code: Output:
empty_tuple = () Empty tuple: ()
print("Empty tuple: ", empty_tuple) Tuple with integers: (4, 6, 8, 10, 12, 14)
Tuple with different data types: (4, 'Python', 9.3)
int_tuple = (4, 6, 8, 10, 12, 14) A nested tuple: ('Python', {4: 5, 6: 2, 8: 2}, (5, 3, 5, 6))
print("Tuple with integers: ", int_tuple)
mixed_tuple = (4, "Python", 9.3)
print("Tuple with different data types: ", mixed_tuple)
nested_tuple = ("Python", {4: 5, 6: 2, 8:2}, (5, 3, 5, 6))
print("A nested tuple: ", nested_tuple)
Tuples can be constructed without using parentheses. This is known as triple packing.
Code
tuple_ = 4, 5.7, "Tuples", ["Python", "Tuples"]
print(tuple_)
print(type(tuple_) ) Output:
try: (4, 5.7, 'Tuples', ['Python', 'Tuples'])
tuple_[1] = 4.2 <class 'tuple'>
<class 'TypeError'>
except:
print(TypeError )
The construction of a tuple from a single member might be hard.
Simply adding parenthesis around the element is insufficient. To be recognised as a tuple, the element must
be followed by a comma.
Code
single_tuple = ("Tuple") Output:
print( type(single_tuple) ) <class 'str'>
single_tuple = ("Tuple",) <class 'tuple'>
print( type(single_tuple) ) <class '
single_tuple = "Tuple",
print( type(single_tuple) )
tuple'>
Accessing Tuple Elements
We can access the objects of a tuple in a variety of ways.
o Indexing
To access an object of a tuple, we can use the index operator [], where indexing in the tuple starts from 0.
A tuple with 5 items will have indices ranging from 0 to 4. An IndexError will be raised if we try to access
an index from the tuple that is outside the range of the tuple index. In this case, an index above 4 will be out
of range.
We cannot give an index of a floating data type or other kinds because the index in Python must be an
integer. TypeError will appear as a result if we give a floating index.
The example below illustrates how indexing is performed in nested tuples to access elements.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print(tuple_[0])
print(tuple_[1]) Output:
try: Python
print(tuple_[5]) Tuple
except Exception as e: tuple index out of range
tuple indices must be integers or
print(e)
slices, not float
try: l
print(tuple_[1.0]) 6
except Exception as e:
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS
III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:8
print(e)
nested_tuple = ("Tuple", [4, 6, 2, 6], (6, 2, 6, 7))
print(nested_tuple[0][3])
print(nested_tuple[1][1])
o Negative Indexing
Python's sequence objects support negative indexing.
The last item of the collection is represented by -1, the second last item by -2, and so on.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Collection")
print("Element at -1 index: ", tuple_[-1])
print("Elements between -4 and -1 are: ", tuple_[-4:-1])
Output:
Element at -1 index: Collection
Elements between -4 and -1 are: ('Python', 'Tuple', 'Ordered')

Slicing
In Python, tuple slicing is a common practise and the most popular method for programmers to handle
practical issues. Think about a Python tuple. To access a variety of elements in a tuple, you must slice it.
One approach is to use the colon as a straightforward slicing operator (:).
We can use a slicing operator, a colon (:), to access a range of tuple elements.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
print("Elements between indices 1 and 3: ", tuple_[1:3])
print("Elements between indices 0 and -4: ", tuple_[:-4])
print("Entire tuple: ", tuple_[:])
Output:
Elements between indices 1 and 3: ('Tuple', 'Ordered')
Elements between indices 0 and -4: ('Python', 'Tuple')
Entire tuple: ('Python', 'Tuple', 'Ordered', 'Immutable', 'Collection', 'Objects')
Deleting a Tuple
A tuple's components cannot be altered, as was previously said. As a result, we are unable to get rid of or
remove tuple components.
However, a tuple can be totally deleted with the keyword del.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Objects")
try:
del tuple_[3]
print(tuple_)
except Exception as e:
print(e)
del tuple_
try:
print(tuple_)
except Exception as e:
print(e)
Output:
'tuple' object does not support item deletion
name 'tuple_' is not defined
Repetition Tuples in Python
Code
tuple_ = ('Python',"Tuples")
print("Original tuple is: ", tuple_)
tuple_ = tuple_ * 3
print("New tuple is: ", tuple_)
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS
III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:9

Output:
Original tuple is: ('Python', 'Tuples')
New tuple is: ('Python', 'Tuples', 'Python', 'Tuples', 'Python', 'Tuples')
Tuple Methods
Python Tuples is a collection of immutable objects that is more like to a list. Python offers a few ways to
work with tuples. These two approaches will be thoroughly covered in this essay with the aid of some
examples.
Examples of these methods are given below.
Count ( ) Method
The number of times the specified element occurs in the tuple is returned by the count () function of Tuple.
Code
T1 = (0, 1, 5, 6, 7, 2, 2, 4, 2, 3, 2, 3, 1, 3, 2)
T2 = ('python', 'java', 'python', 'Tpoint', 'python', 'java')
res = [Link](2)
print('Count of 2 in T1 is:', res)
res = [Link]('java')
print('Count of Java in T2 is:', res)
Output:
Count of 2 in T1 is: 5
Count of java in T2 is: 2
Index() Method:
The first instance of the requested element from the tuple is returned by the Index() function.
Parameters:
The element to be looked for.
o begin (Optional): the index used as the starting point for searching
o final (optional): The last index up until which the search is conducted
o Index() Method
Code
Tuple_data = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = Tuple_data.index(3)
print('First occurrence of 1 is', res)
res = Tuple_data.index(3, 4)
print('First occurrence of 1 after 4th index is:', res)
Output:
First occurrence of 1 is 2
First occurrence of 1 after 4th index is: 6
Tuple Membership Test
Using the in keyword, we can determine whether an item is present in the given tuple or not.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", "Collection", "Ordered")
print('Tuple' in tuple_)
print('Items' in tuple_)
print('Immutable' not in tuple_)
print('Items' not in tuple_)
Output:
True
False
False
True

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS


III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:10

Iterating Through a Tuple


We can use a for loop to iterate through each element of a tuple.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
for item in tuple_:
print(item)
Output:
Python
Tuple
Ordered
Immutable
Changing a Tuple
Tuples, as opposed to lists, are immutable objects.
This suggests that we are unable to change a tuple's elements once they have been defined. The nested
elements of an element can be changed, though, if the element itself is a changeable data type like a list.
A tuple can be assigned to many values (reassignment).
Code
tuple_ = ("Python", "Tuple", "Ordered", "Immutable", [1,2,3,4])
try:
tuple_[2] = "Items"
print(tuple_)
except Exception as e:
print( e )
tuple_[-1][2] = 10
print(tuple_)
tuple_ = ("Python", "Items")
print(tuple_)
Output:
'tuple' object does not support item assignment
('Python', 'Tuple', 'Ordered', 'Immutable', [1, 2, 10, 4])
('Python', 'Items')
Concatenation of the Tuples
To merge multiple tuples, we can use the + operator. Concatenation is the term for [Link] the * operator,
we may also repeat a tuple's elements for a specified number of times. This is already shown above.
The results of the operations + and * are new tuples.
Code
tuple_ = ("Python", "Tuple", "Ordered", "Immutable")
print(tuple_ + (4, 5, 6))
Output:
('Python', 'Tuple', 'Ordered', 'Immutable', 4, 5, 6)
Tuples have the following advantages over lists:
o Triples take less time than lists do.
o Due to tuples, the code is protected from accidental modifications. It is desirable to store
non-changing information in "tuples" instead of "records" if a program expects it.
o A tuple can be used as a dictionary key if it contains immutable values like strings, numbers,
or another tuple. "Lists" cannot be utilized as dictionary keys because they are mutable.

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS


III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:11

Differences between List and Tuple in Python


Sno LIST TUPLE

1 Lists are mutable Tuples are immutable

The implication of iterations is Time- The implication of iterations is


2
consuming comparatively Faster

The list is better for performing operations, A Tuple data type is appropriate for
3
such as insertion and deletion. accessing the elements

Tuple consumes less memory as


4 Lists consume more memory
compared to the list

Tuple does not have many built-in


5 Lists have several built-in methods
methods.

Unexpected changes and errors are more


6 In a tuple, it is hard to take place.
likely to occur

Python List vs Python Tuple


DICTIONARIES IN PYTHON
Python provides another composite data type called a dictionary, which is similar to a list in that it is a
collection of objects.
Dictionaries and lists share the following characteristics:
 Both are mutable.
 Both are dynamic. They can grow and shrink as needed.
 Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A
dictionary can also contain a list, and vice versa.
Dictionaries differ from lists primarily in how elements are accessed:
 List elements are accessed by their position in the list, via indexing.
 Dictionary elements are accessed via keys.
Dictionary in Python is a collection of keys values, used to store data values like a map, which, unlike
other data types which hold only a single value as an element.
Example of Dictionary in Python
Dictionary holds key:value pair. Key-Value is provided in the dictionary to make it more optimized.
EXAMPLE
Dict = {1: 'Python', 2: 'For', 3: 'Programming'}
print(Dict)

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS


III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:12

Output:
{1: 'Python', 2: 'For', 3: 'Programming'}
Creating a Dictionary
In Python, a dictionary can be created by placing a sequence of elements within curly {} braces, separated
by ‘comma’. Dictionary holds pairs of values, one being the Key and the other corresponding pair element
being its Key:value. Values in a dictionary can be of any data type and can be duplicated, whereas keys
can’t be repeated and must be immutable.
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be treated
distinctly.
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Output:
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{'Name': 'Geeks', 1: [1, 2, 3, 4]}
Dictionary can also be created by the built-in function dict(). An empty dictionary can be created by just
placing to curly braces{}.
Dict = {}
print("Empty Dictionary: ") Output:
print(Dict) Empty Dictionary:
Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'}) {}
print("\nDictionary with the use of dict(): ") Dictionary with the use of dict():
print(Dict) {1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dict = dict([(1, 'Geeks'), (2, 'For')]) Dictionary with each item as a pair:
print("\nDictionary with each item as a pair: ") {1: 'Geeks', 2: 'For'}
print(Dict)
Complexities for Creating a Dictionary:
Time complexity: O(len(dict))
Space complexity: O(n)
Nested Dictionary

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS


III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:13

Dict = {1: 'Geeks', 2: 'For',


3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}

print(Dict)
Output:
{1: 'Geeks', 2: 'For', 3: {'A': 'Welcome', 'B': 'To', 'C': 'Geeks'}}
Adding elements to a Dictionary
Addition of elements can be done in multiple ways. One value at a time can be added to a Dictionary by
defining value along with the key e.g. Dict[Key] = ‘Value’. Updating an existing value in a Dictionary can
be done by using the built-in update() method. Nested key values can also be added to an existing
Dictionary.
Note- While adding a value, if the key-value already exists, the value gets updated otherwise a new Key
with the value is added to the Dictionary.

Dict = {}
print("Empty Dictionary: ") Output:
print(Dict) Empty Dictionary:
{}
Dict[0] = 'Geeks' Dictionary after adding 3 elements:
Dict[2] = 'For' {0: 'Geeks', 2: 'For', 3: 1}
Dict[3] = 1 Dictionary after adding 3 elements:
print("\nDictionary after adding 3 elements: ") {0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
print(Dict) Updated key value:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Dict['Value_set'] = 2, 3, 4 Adding a Nested Key:
print("\nDictionary after adding 3 elements: ") {0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5:
print(Dict) {'Nested': {'1': 'Life', '2': 'Geeks'}}}

Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)

Dict[5] = {'Nested': {'1': 'Life', '2': 'Geeks'}}


print("\nAdding a Nested Key: ")
print(Dict)

Complexities for Adding elements in a Dictionary:


Time complexity: O(1)/O(n)
Space complexity: O(1)
Accessing elements of a Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets.
# Python program to demonstrate
# accessing a element from a Dictionary

# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key


print("Accessing a element using key:")
print(Dict['name'])
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS
III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:14

# accessing a element using key


print("Accessing a element using key:")
print(Dict[1])
Output:
Accessing a element using key:
For
Accessing a element using key:
Geeks
There is also a method called get() that will also help in accessing the element from a [Link]
method accepts key as argument and returns the value.
Complexities for Accessing elements in a Dictionary:
Time complexity: O(1)
Space complexity: O(1)
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using get()
# method
print("Accessing a element using get:")
print([Link](3))
Output:
Accessing a element using get:
Geeks
Accessing an element of a nested dictionary
In order to access the value of any key in the nested dictionary, use indexing [] syntax.
# Creating a Dictionary
Dict = {'Dict1': {1: 'Geeks'},
'Dict2': {'Name': 'For'}}
# Accessing element using key
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
Output:
{1: 'Geeks'}
Geeks
For
Deleting Elements using del Keyword
The items of the dictionary can be deleted by using the del keyword as given below.
# Python program to demonstrate
# Deleting Elements using del Keyword

# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

print("Dictionary =")
print(Dict)
#Deleting some of the Dictionar data
del(Dict[1])
print("Data after deletion Dictionary=")
print(Dict)
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS
III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:15

Output
Dictionary ={1: 'Geeks', 'name': 'For', 3: 'Geeks'}
Data after deletion Dictionary={'name': 'For', 3: 'Geeks'}
Dictionary methods
Method Description

[Link]() Remove all the elements from the dictionary

[Link]() Returns a copy of the dictionary

[Link](key, default = “None”) Returns the value of specified key

[Link]() Returns a list containing a tuple for each key value pair

[Link]() Returns a list containing dictionary’s keys

[Link](dict2) Updates dictionary with specified key-value pairs

[Link]() Returns a list of all the values of dictionary

pop() Remove the element with specified key

popItem() Removes the last inserted key-value pair

[Link](key,default= set the key to the default value if the key is not specified in the
“None”) dictionary

dict.has_key(key) returns true if the dictionary contains the specified key.

[Link](key, default = “None”) used to get the value specified for the passed key.

# demo for all dictionary methods


dict1 = {1: "Python", 2: "Java", 3: "Ruby", 4: "Scala"}

# copy() method
dict2 = [Link]()
print(dict2)

# clear() method
[Link]()
print(dict1)

# get() method
print([Link](1))
RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS
III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:16

# items() method
print([Link]())

# keys() method
print([Link]())

# pop() method
[Link](4)
print(dict2)

# popitem() method
[Link]()
print(dict2)

# update() method
[Link]({3: "Scala"})
print(dict2)

# values() method
print([Link]())
Output:
{1: 'Python', 2: 'Java', 3: 'Ruby', 4: 'Scala'}
{}
Python
dict_items([(1, 'Python'), (2, 'Java'), (3, 'Ruby'), (4, 'Scala')])
dict_keys([1, 2, 3, 4])
{1: 'Python', 2: 'Java', 3: 'Ruby'}
{1: 'Python', 2: 'Java'}
{1: 'Python', 2: 'Java', 3: 'Scala'}
dict_values(['Python', 'Java', 'Scala'])

Difference between a List and a Dictionary


The following table shows some differences between a list and a dictionary in Python:
List Dictionary

The dictionary is a hashed structure of the key


The list is a collection of index value pairs like
and value
that of the array in C++.
pairs.

The dictionary is created by placing elements


The list is created by placing elements
in { } as “key”:”value”, each key-value pair is
in [ ] separated by commas “,”
separated by commas “, “

The indices of the list are integers starting The keys of the dictionary can be of any data
from 0. type.

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS


III BSC(CS) UNIT-IV – PYTHON PROGRAMMING Page No.:17

List Dictionary

The elements are accessed via indices. The elements are accessed via key-value pairs.

The order of the elements entered is


There is no guarantee for maintaining order.
maintained.

Lists are orders, mutable, and can contain Dictionaries are unordered and mutable but they
duplicate values. cannot contain duplicate keys.

--------------------- X ----------------------

RAJESWARI COLLEGE OF ARTS AND SCIENCE FOR WOMEN,[Link] DEVI-DEPT. OF CS

You might also like