Ⅳ SEM BCA PYTHON
Unit - 2
STRINGS
A string is a data structure in Python that represents a sequence of
characters. It is an immutable data type, meaning that once you have created a
string, you cannot change it. Strings are used for storing and manipulating text
data, representing names, addresses, and other types of data that can be
represented as text.
Example:
"Sapient" or 'Sapient '
Python does not have a character data type, a single character is simply
a string with a length of 1.
Square brackets can be used to access elements of the string.
Creating a String in Python
Strings in Python can be created using single quotes or double quotes or even
triple quotes.
Example:
string1=‟Sapient‟
string2=”Sapient”
string3=‟‟‟Sapient‟‟‟
Accessing characters in Python String
In Python, individual characters of a String can be accessed by using the
method of Indexing. Indexing allows negative address references to access
characters from the back of the String, e.g. -1 refers to the last character, -2
refers to the second last character, and so on.
While accessing an index out of the range will cause an IndexError.
Only Integers are allowed to be passed as an index, float or other types that will
cause a TypeError.
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 1
Ⅳ SEM BCA PYTHON
# Python Program to Access
# characters of String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing First character
print("\nFirst character of String is: ")
print(String1[0])
# Printing Last character
print("\nLast character of String is: ")
print(String1[-1])
Output:
Initial String:
GeeksForGeeks
First character of String is:
Last cha racter of String is:
The str() function
The str() function is used to convert the specified value into a string.
Syntax:
str(object='')
str(object=b'', encoding='utf-8', errors='strict')
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 2
Ⅳ SEM BCA PYTHON
Parameter:
Name Description
object Any object.
encoding The encoding of the given object. Default is UTF-8.
errors Specifies what to do if the decoding fails.
Return value:
A string.
Example: Python str() function
print(str(15))
Output:
15
Example: Python str() function
# Python program to demonstrate
# str()
a = bytes("ŽString", encoding = 'utf-8')
s = str(a, encoding = "ascii", errors ="ignore")
print(s)
Output:
String
In the above example, the character Ž should raise an error as it cannot be
decoded by ASCII. But it is ignored because the errors are set as ignore.
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 3
Ⅳ SEM BCA PYTHON
Exceptions of str() in Python
There are six types of error taken by this function.
strict (default): it raises a UnicodeDecodeError.
ignore: It ignores the unencodable Unicode
replace: It replaces the unencodable Unicode with a question mark
xmlcharrefreplace: It inserts XML character reference instead of the
unencodable Unicode
backslashreplace: inserts a \uNNNN Espace sequence instead of an
unencodable Unicode
namereplace: inserts a \N{…} escape sequence instead of an unencodable
Unicode
Operations on Strings
1. Concatenation
String concatenation means add strings together.Use the + character to
add a variable to another variable.
x = "Python is "
y = "awesome"
z= x+y
print(z)
To add a space between them, add a " ":
a = "Hello"
b = "World"
c=a+""+b
print(c)
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 4
Ⅳ SEM BCA PYTHON
2. Comparison
Method 1: Using Relational Operators
The relational operators compare the Unicode values of the characters of the
strings from the zeroth index till the end of the string. It then returns a boolean
value according to the operator used.
print("Geek" == "Geek")
print("Geek" < "geek")
print("Geek" > "geek")
print("Geek" != "Geek")
output- TRUE
TRUE
FALSE
FALSE
“Geek” == “Geek” will return True as the Unicode of all the characters are equal
In case of “Geek” and “geek” as the unicode of G is \u0047 and of g is \u0067
“Geek” < “geek” will return True and “Geek” > “geek” will return False
Method 2: Using is and is not
The == operator compares the values of both the operands and checks for value
equality. Whereas is operator checks whether both the operands refer to the
same object or not. The same is the case for != and is not.
3. Slicing
String slicing in Python is about obtaining a sub-string from the given string by
slicing it respectively from start to end.
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 5
Ⅳ SEM BCA PYTHON
Method 1: Using the slice() method
The slice() constructor creates a slice object representing the set of indices
specified by range(start, stop, step).
Syntax:
slice(stop)
slice(start, stop, step)
Parameters: start: Starting index where the slicing of object starts.
stop: Ending index where the slicing of object stops.
step: It is an optional argument that determines the increment between each
index for slicing.
Return Type:: Returns a sliced object containing elements in the given range
only.
String = 'ASTRING'
# Using slice constructor
s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
Output:
String slicing
AST
SR
GITA
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 6
Ⅳ SEM BCA PYTHON
Method 2: Using the List/array slicing [ :: ] method
In Python, indexing syntax can be used as a substitute for the slice object. A
start, end, and step have the same mechanism as the slice() constructor.
Syntax
arr[start:stop] # items start through stop-1
arr[start:] # items start through the rest of the array
arr[:stop] # items from the beginning through stop-1
arr[:] # a copy of the whole array
arr[start:stop:step] # start through not past stop, by step
4. Joining
Python join() is an inbuilt string function in Python used to join elements of
the sequence separated by a string separator. This function joins elements of a
sequence and makes it a string.
Example:
str = '-'.join('hello')
print(str)
Output:
h-e-l-l-o
Python String join() Syntax
Syntax: string_name.join(iterable)
Parameters:
Iterable – objects capable of returning their members one at a time. Some
examples are List, Tuple, String, Dictionary, and Set
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 7
Ⅳ SEM BCA PYTHON
Return Value: The join() method returns a string concatenated with the
elements of iterable.
Type Error: If the iterable contains any non-string values, it raises a TypeError
exception.
# Joining with empty separator
list1 = ['g', 'e', 'e', 'k', 's']
print("".join(list1))
# Joining with string
list1 = " geeks "
print("$".join(list1))
Output:
geeks
$g$e$e$k$s$
5. Traversing
How to iterate over the characters of a string in Python.
#1: Using simple iteration and range()
string_name = "geeksforgeeks"
# Iterate over the string
for element in string_name:
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 8
Ⅳ SEM BCA PYTHON
print(element, end=' ')
print("\n")
string_name = "GEEKS"
# Iterate over index
for element in range(0, len(string_name)):
print(string_name[element])
Output:
geeksforgeeks
#2: Using enumerate() function
# Python program to iterate over characters of a string
string_name = "Geeks"
# Iterate over the string
for i, v in enumerate(string_name):
print(v)
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 9
Ⅳ SEM BCA PYTHON
Output:
#3: Iterate characters in reverse order
# Python program to iterate over characters of a string
string_name = "GEEKS"
# slicing the string in reverse fashion
for element in string_name[ : :-1]:
print(element, end =' ')
print('\n')
Output:
SKEEG
Format Specifiers
String formatting
String formatting is the process of infusing things in the string dynamically
and presenting the string.
There are four different ways to perform string formatting in Python:
Formatting with % Operator.
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 10
Ⅳ SEM BCA PYTHON
Formatting with format() string method.
Formatting with string literals, called f-strings.
Formatting with String Template Class
Formatting with center() string method.
Method 1: Formatting string using % Operator
It is the oldest method of string formatting. Here we use the
modulo % operator. The modulo % is also known as the “string-formatting
operator”.
print("The mangy, scrawny stray dog %s gobbled down"
%'hurriedly' +
"the grain-free, organic dog food.")
Output:
The mangy, scrawny stray dog hurriedly gobbled down the grain-free, organic
dog food.
‘%s’ is used to inject strings similarly ‘%d’ for integers, ‘%f’ for floating-point
values, ‘%b’ for binary forma
Method 2: Formatting string using format() method
Formatters work by putting in one or more replacement fields and placeholders
defined by a pair of curly braces { } into a string and calling the str.format().
The value we wish to put into the placeholders and concatenate with the string
passed as parameters into the format function.
Syntax: „String here {} then also {}‟.format(„something1′,‟something2‟)
print('We all are {}.'.format('equal'))
Output:
We all are equal.
We can insert object by using index-based position:
Python3
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 11
Ⅳ SEM BCA PYTHON
print('{2} {1} {0}'.format('directions',
'the', 'Read'))
Output:
Read the directions.
Method 3: Formatted String using F-strings
String Interpolation or more commonly as F-strings (because of the leading f
character preceding the string literal). The idea behind f-strings is to make
string interpolation simpler.
To create an f-string, prefix the string with the letter “ f ”. The string itself can
be formatted in much the same way that you would with str.format()
name = 'Ele'
print(f"My name is {name}.")
Output:
My name is Ele.
Method 4: String Template Class
In the String module, Template Class allows us to create simplified syntax for
output specification. The format uses placeholder names formed by $ with valid
Python identifiers (alphanumeric characters and underscores). Surrounding
the placeholder with braces allows it to be followed by more alphanumeric
letters with no intervening spaces. Writing $$ creates a single escaped $:
# Python program to demonstrate
# string interpolation
from string import Template
n1 = 'Hello'
n2 = 'GeeksforGeeks'
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 12
Ⅳ SEM BCA PYTHON
# made a template which we used to
# pass two variable so n3 and n4
# formal and n1 and n2 actual
n = Template('$n3 ! This is $n4.')
# and pass the parameters into the
# template string.
print(n.substitute(n3=n1, n4=n2))
Output:
Hello ! This is GeeksforGeeks.
Method 5: String center() method
The center() method is a built-in method in Python‟s str class that returns a
new string that is centered within a string of a specified width.
string = "GeeksForGeeks!"
width = 30
centered_string = string.center(width)
print(centered_string)
Output
GeeksForGeeks!
Escape Sequences
Let's suppose we need to write the text as - They said, "Hello what's going on?"-
the given statement can be written in single quotes or double quotes but it will
raise the SyntaxError as it contains both single and double-quotes.
Example
Consider the following example to understand the real use of Python operators.
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 13
Ⅳ SEM BCA PYTHON
str = "They said, "Hello what's going on?""
print(str)
Output:
SyntaxError: invalid syntax
The backslash(/) symbol denotes the escape sequence. The backslash can be
followed by a special character and it interpreted differently.
The list of an escape sequence is given below:
Sr. Escape Description Example
Sequence
1. \newline It ignores the new line. print("Python1 \
Python2 \
Python3")
Output:
Python1 Python2 Python3
2. \\ Backslash print("\\")
Output:
\
3. \' Single Quotes print('\'')
Output:
'
4. \\'' Double Quotes print("\"")
Output:
"
5. \a ASCII Bell print("\a")
6. \b ASCII Backspace(BS) print("Hello \b World")
Output:
Hello World
7. \f ASCII Formfeed print("Hello \f World!")
Hello World!
8. \n ASCII Linefeed print("Hello \n World!")
Output:
Hello
World!
9. \r ASCII Carriege print("Hello \r World!")
Return(CR) Output:
World!
10. \t ASCII Horizontal Tab print("Hello \t World!")
Output:
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 14
Ⅳ SEM BCA PYTHON
Hello World!
11. \v ASCII Vertical Tab print("Hello \v World!")
Output:
Hello
World!
12. \ooo Character with octal print("\110\145\154\154\157")
value Output:
Hello
13 \xHH Character with hex print("\x48\x65\x6c\x6c\x6f")
value. Output:
Hello
Raw and Unicode Strings
In Python, when you prefix a string with the letter r or R such as r'...' and R'...',
that string becomes a raw string. Unlike a regular string, a raw string treats
the backslashes (\) as literal characters.
Raw strings are useful when you deal with strings that have many
backslashes, for example, regular expressions or directory paths on Windows.
Normal strings in Python are stored internally as 8-bit ASCII, while Unicode
strings are stored as 16-bit Unicode. This allows for a more varied set of
characters, including special characters from most languages in the world.
#!/usr/bin/python
print u'Hello, world!'
When the above code is executed, it produces the following result −
Hello, world!
As you can see, Unicode strings use the prefix u, just as raw strings use the
prefix r
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 15
Ⅳ SEM BCA PYTHON
Python String MethodsTable
Python String Methods
Function
Name Description
Converts the first character of the string to a capital
capitalize()
(uppercase) letter
casefold() Implements caseless string matching
center() Pad the string with the specified character.
Returns the number of occurrences of a substring in the
count()
string.
encode() Encodes strings with the specified encoded scheme
endswith() Returns “True” if a string ends with the given suffix
Specifies the amount of space to be substituted with the “\t”
expandtabs()
symbol in the string
find() Returns the lowest index of the substring if it is found
format() Formats the string for printing it to console
format_map() Formats specified values in a string using a dictionary
Returns the position of the first occurrence of a substring in
index()
a string
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 16
Ⅳ SEM BCA PYTHON
Function
Name Description
Checks whether all the characters in a given string is
isalnum()
alphanumeric or not
isalpha() Returns “True” if all characters in the string are alphabets
isdecimal() Returns true if all characters in a string are decimal
isdigit() Returns “True” if all characters in the string are digits
isidentifier() Check whether a string is a valid identifier or not
islower() Checks if all characters in the string are lowercase
Returns “True” if all characters in the string are numeric
isnumeric()
characters
Returns “True” if all characters in the string are printable or
isprintable()
the string is empty
Returns “True” if all characters in the string are whitespace
isspace()
characters
istitle() Returns “True” if the string is a title cased string
isupper() Checks if all characters in the string are uppercase
join() Returns a concatenated String
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 17
Ⅳ SEM BCA PYTHON
Function
Name Description
ljust() Left aligns the string according to the width specified
lower() Converts all uppercase characters in a string into lowercase
lstrip() Returns the string with leading characters removed
maketrans() Returns a translation table
partition() Splits the string at the first occurrence of the separator
Replaces all occurrences of a substring with another
replace()
substring
rfind() Returns the highest index of the substring
rindex() Returns the highest index of the substring inside the string
rjust() Right aligns the string according to the width specified
rpartition() Split the given string into three parts
rsplit() Split the string from the right by the specified separator
rstrip() Removes trailing characters
splitlines() Split the lines at line boundaries
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 18
Ⅳ SEM BCA PYTHON
Function
Name Description
startswith() Returns “True” if a string starts with the given prefix
strip() Returns the string with both leading and trailing characters
Converts all uppercase characters to lowercase and vice
swapcase()
versa
title() Convert string to title case
translate() Modify string according to given translation mappings
upper() Converts all lowercase characters in a string into uppercase
Returns a copy of the string with „0‟ characters padded to the
zfill()
left side of the string
LISTS
Creating List
The list is a sequence data type which is used to store the collection ofdata. A
single list may contain DataTypes like Integers, Strings, as well as Objects.
Lists are mutable, and hence, they can be altered even after their creation.
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.
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 19
Ⅳ SEM BCA PYTHON
# Creating a List
List = []
print("Blank List: ")
print(List)
# Creating a List of numbers
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)
# Creating a List of strings and accessing
# using index
List = ["Geeks", "For", "Geeks"]
print("\nList Items: ")
print(List[0])
print(List[2])
Output
Blank List:
[]
List of numbers:
[10, 20, 14]
List Items:
Geeks
Geeks
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 20
Ⅳ SEM BCA PYTHON
Operations on List
Built in Functions on Lists
Python includes the following list functions −
Sr.No Function with Description
1 cmp(list1, list2)Compares elements of both lists.
2 len(list)Gives the total length of the list.p>
3 max(list)Returns item from the list with max value.
4 min(list)Returns item from the list with min value.
5 list(seq)Converts a tuple into list.
Python includes following list methods
Sr.No Methods with Description
1 list.append(obj)Appends object obj to list
2 list.count(obj)Returns count of how many times obj occurs in list
3 list.extend(seq)Appends the contents of seq to list
4 list.index(obj)Returns the lowest index in list that obj appears
5 list.insert(index, obj)Inserts object obj into list at offset index
6 list.pop(obj=list[-1])Removes and returns last object or obj from list
7 list.remove(obj)Removes object obj from list
8 list.reverse()Reverses objects of list in place
9 list.sort([func])Sorts objects of list, use compare func if given
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 21
Ⅳ SEM BCA PYTHON
Implementation of Stacks and Queues using Lists
Stack works on the principle of “Last-in, first-out”. Also, the inbuilt functions
in Python make the code short and simple. To add an item to the top of the list,
i.e., to push an item, we use append() function and to pop out an element we
use pop() function.
Example:
stack = ["Amar", "Akbar", "Anthony"]
stack.append("Ram")
stack.append("Iqbal")
print(stack)
# Removes the last item
print(stack.pop())
print(stack)
# Removes the last item
print(stack.pop())
print(stack)
Output:
['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']
Iqbal
['Amar', 'Akbar', 'Anthony', 'Ram']
Ram
['Amar', 'Akbar', 'Anthony']
Queue works on the principle of “First-in, first-out”. Below is list
implementation of queue. We use pop(0) to remove the first item from a list.
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 22
Ⅳ SEM BCA PYTHON
queue = ["Amar", "Akbar", "Anthony"]
queue.append("Ram")
queue.append("Iqbal")
print(queue)
# Removes the first item
print(queue.pop(0))
print(queue)
Output:
['Amar', 'Akbar', 'Anthony', 'Ram', 'Iqbal']
Amar
['Akbar', 'Anthony', 'Ram', 'Iqbal']
Nested Lists
A list within another list is referred to as a nested list in Python.
MyList = [[22, 14, 16], ["Joe", "Sam", "Abel"], [True, False, True]]
To access the elements in this nested list we use indexing. To access an
element in one of the sublists, we use two indices – the index of the sublist and
the index of the element within the sublist.
#printing a sublist
print(MyList[0])
#output [22, 14, 16]
# printing an element within a sublist
print(MyList[0][1]) #output: 14
# modifying an element in a sublist
MyList[0][1] = 20
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 23
Ⅳ SEM BCA PYTHON
print(MyList) #output:[[22, 20, 16], ["Joe", "Sam", "Abel"], [True, False, True]]
Dictionaries
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.
Dictionary holds key:value pair. Key-Value is provided in the dictionary to
make it more optimized.
Creating Dictionaries
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.
country_capitals = {
"United States": "Washington D.C.",
"Italy": "Rome",
"England": "London"
}
# printing the dictionary
print(country_capitals)
Operation on Dictionaries
1. Definition operations
These operations allow us to define or create a dictionary.
1.1.{ }
Creates an empty dictionary or a dictionary with some initial values.
y = {}
x = {1: "one", 2: "two", 3: "three"}
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 24
Ⅳ SEM BCA PYTHON
2. Mutable operations
These operations allow us to work with dictionaries, but altering or modifying
their previous definition.
2.1. [ ]
Adds a new pair of key and value to the dictionary, but in case that the key
already exists in the dictionary, we can update the value.
y = {}
y['one'] = 1
y['two'] = 2
print(y)
Output:{'one': 1, 'two': 2}
2.2. del
Del statement can be used to remove an entry (key-value pair) from a
dictionary.
y = {'one': 1, 'two': 2}print(y)Output:{'one': 1, 'two': 2}del
y['two']print(y)Output:{'one': 1}
2.3. update
This method updates a first dictionary with all the key-value pairs of a second
dictionary. Keys that are common to both dictionaries, the values from the
second dictionary override those of the first.
x = {'one': 0, 'two': 2}
y = {'one': 1, 'three': 3}
x.update(y)print(x)
Output:{'one': 1, 'two': 2, 'three': 3}
3. Immutable operations
These operations allow us to work with dictionaries without altering or
modifying their previous definition.
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 25
Ⅳ SEM BCA PYTHON
3.1. len
Returns the number of entries (key-value pairs) in a dictionary.
x = {'one': 0, 'two': 2}
print(len(x))
Output:2
3.2. keys
This method allows you to get all the keys in the dictionary. It is often used in a
“for loop” to iterate over the content of a dictionary.
x = {'one': 1, 'two': 2}
print(x.keys())
Output:dict_keys(['one', 'two'])
3.3. values
This method allows you to obtain all the values stored in a dictionary.
x = {'one': 1, 'two': 2}p
rint(x.values())
Output:dict_values([1, 2])
3.4. items
Returns all the keys and their associated values as a sequence of tuples.
x = {'one': 1, 'two': 2}
print(x.items())
Output:dict_items([('one', 1), ('two', 2)])
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 26
Ⅳ SEM BCA PYTHON
3.5. in
Attempting to access a key that is not in a dictionary will raise an exception. To
handle this exception, you can use the in method that test whether a key exists
in a dictionary, returns True if a dictionary has a value stored under the given
key and False otherwise.
y = {'one': 1, 'two': 2}
del y['three']
Output:KeyError: 'three'
y = {'one': 1, 'two': 2}
if 'three' in y:
del y['three']
print(y)
Output:{'one': 1, 'two': 2}
3.6. get
Returns the value associated with a key if the dictionary contains that key, in
case that the dictionary does not contain the key, you can specified a second
optional argument to return a default value, if the argument is not included get
method will return None.
y = {'one': 1, 'two': 2}
print(y.get('one'))
print(y.get('three'))
print(y.get('three', 'The key does not exist.'))
Output:1
None
The key does not exist.
3.7. setdefault
This method is similar to get method, it returns the value associated with a key
if the dictionary contains that key, but in case that the dictionary does not
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 27
Ⅳ SEM BCA PYTHON
contain the key, this method will create a new element in the dictionary (key-
value pair), where the first argument in this method is the key, and the second
argument is the value. The second argument is optional, but if this is not
included, the value will be None.
y = {'one': 1, 'two': 2}
print(y.setdefault('three', '3'))
print(y.setdefault('two', 'dos'))
print(y)
Output:3
{'one': 1, 'two': 2, 'three': '3'}
Built in functions on Dictionaries
Python includes the following dictionary functions −
Sr.No Function with Description
1 cmp(dict1, dict2)Compares elements of both dict.
2 len(dict)Gives the total length of the dictionary. This
would be equal to the number of items in the
dictionary.
3 str(dict)Produces a printable string representation of a
dictionary
4 type(variable)Returns the type of the passed variable.
If passed variable is dictionary, then it would return a
dictionary type.
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 28
Ⅳ SEM BCA PYTHON
Dictionary Methods
Dictionary methods
Method Description
Remove all the elements from the
dic.clear()
dictionary
dict.copy() Returns a copy of the dictionary
dict.get(key, default = “None”) Returns the value of specified key
Returns a list containing a tuple for each
dict.items()
key value pair
Returns a list containing dictionary‟s
dict.keys()
keys
Updates dictionary with specified key-
dict.update(dict2)
value pairs
Returns a list of all the values of
dict.values()
dictionary
pop() Remove the element with specified key
popItem() Removes the last inserted key-value pair
dict.setdefault(key,default= set the key to the default value if the key
“None”) is not specified in the dictionary
returns true if the dictionary contains the
dict.has_key(key)
specified key.
used to get the value specified for the
dict.get(key, default = “None”)
passed key.
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 29
Ⅳ SEM BCA PYTHON
Populating Dictionaries
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.
Python3
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements one at a time
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# to a single Key
Dict['Value_set'] = 2, 3, 4
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 30
Ⅳ SEM BCA PYTHON
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested': {'1': 'Life', '2': 'Geeks'}}
print("\nAdding a Nested Key: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5:
{'Nested': {'1': 'Life', '2': 'Geeks'}}}
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 31
Ⅳ SEM BCA PYTHON
Traversing Dictionaries
A dictionary is an ordered collection of items .Meaning a dictionary maintains
the order of its items.
We can iterate through dictionary keys one by one using a for loop.
country_capitals = {
"United States": "New York",
"Italy": "Naples"
}
# print dictionary keys one by one
for country in country_capitals:
print(country)
print("----------")
# print dictionary values one by one
for country in country_capitals:
capital = country_capitals[country]
print(capital)
Ms. ASHIKA MUTHANNA, SAPIENT COLLEGE PAGE 32