[go: up one dir, main page]

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

Module 3 Dic Strings

Module 3 of Python Programming covers dictionaries and string manipulation. It explains the dictionary data type, its methods, and how to access, modify, and delete elements, including nested dictionaries. Additionally, it discusses string operations, including escape characters, raw strings, string interpolation, and various string methods.
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 views66 pages

Module 3 Dic Strings

Module 3 of Python Programming covers dictionaries and string manipulation. It explains the dictionary data type, its methods, and how to access, modify, and delete elements, including nested dictionaries. Additionally, it discusses string operations, including escape characters, raw strings, string interpolation, and various string methods.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

PYTHON PROGRAMMING

Module 3
Module 3

Dictionaries and Structuring Data - The


Dictionary Data Type,
Pretty Printing, Using Data Structures to
Model Real-World Things
Manipulating Strings - Working with
Strings, Useful String Methods.
(T1: Chapters 5, 6)
Dictionaries
• A dictionary is an unordered collection of key-value pairs.
• Each pair in the dictionary is represented by a key and value separated by a
colon.
• Dictionaries have keys and values are written with curly brackets.
• A dictionary has a length, specifically the number of key-value pairs.
• A dictionary provides fast look up by key.
• The keys must be immutable object types.
• Dictionaries are indexed by keys, not integers
• Example Dictionary:
my_dict = {'key1': 'value1','key2': 'value2','key3': 'value3'…'keyn': 'valuen'}
Dictionary Items
• Dictionary items are presented in key:value pairs, and can be referred
to by using the key name.
• Multiple items are separated by comas
• In python the items (key:value pairs) are unordered. It means one can
not access items as per specific order.
• References of keys and values are stored in dictionaries.
• Dictionaries are unordered set of elements, the printed order of
elements may or may not be in the order in which we have stored
them in the dictionary.
ACCESSING ENTIRE DICTIONARY by dictionaryname
• Mentioning only the dictionary name without any key prints the
entire dictionary.
• If the key in square bracket is used along with dictionaryname
produces the value that matches the key otherwise error is displayed.
• Example:
• >>> subjectandcode {'Physics': 42, 'Chemistry': 43, 'Mathematics': 41,
'Biology': 44, 'Computer Science': 83, 'Informatics Practices': 65,
'English': 101, 'Hindi': 2}
• >>> subjectandcode["Hindi"]
2
The keys(), values(), and items() Methods
➢ There are three dictionary methods that will return list-like values of the
dictionary’s keys, values, or both keys and values: keys(), values(), and
items().
➢ The values returned by these methods are not true lists: they cannot be
modified and do not have an append() method.
➢ These data types (dict_keys, dict_values, and dict_items, respectively) can
be used in for loops.
The keys(), values(), and items() Methods
➢ Here, a for loop iterates over each of the values in the spam dictionary.
A for loop can also iterate over the keys or both keys and values:

When you use the keys(), values(), and items() methods, a for loop can iterate over the keys, values, or
key-value pairs in a dictionary, respectively. Notice that the values in the dict_items value returned by the
items() method are tuples of the key and value.
The keys(), values(), and items() Methods

➢ If you want a true list from one of these methods, pass its list-like return
value to the list() function.

➢ The list(spam.keys()) line takes the dict_keys value returned from keys()
and passes it to list(), which then returns a list value of ['color', 'age'].
Access Dictionary Keys :Value one by one through Loop

➢ You can also use the multiple assignment trick in a for loop to assign the
key and value to separate variables.
➢ We loop through the key-value pairs in a dictionary using *two* iteration
variables
➢ Each iteration, the first variable is the k for key and
the second variable v is the corresponding value for the key
Checking Whether a Key or Value Exists in a Dictionary

➢ The in and not in operators can check whether a value exists in a list.
➢ You can also use these operators to see whether a certain key or value exists
in a dictionary.

In this example, notice that 'color' in spam is essentially a


shorter version of writing 'color' in spam.keys().

This is always the case: if you ever want to check whether


a value is (or isn’t) a key in the dictionary, you can simply
use the in (or not in) keyword with the dictionary value
itself.
The get() Method

➢ It is used to return the value of a dictionary entry for a specified key.


➢ Fortunately, dictionaries have a get() method that takes two arguments:
• The key and
• A fallback value to return if that key does not exist.
The get() Method

➢ Because there is no 'eggs' key in the picnicItems dictionary, the default value 0
is returned by the get() method.
➢ Without using get(), the code would have caused an error message, such as in
the following example:
The setdefault() Method

➢ You’ll often have to set a value in a dictionary for a certain key only if that key
does not already have a value.

➢ The setdefault() method offers a way to do this in one line of code.


➢ The first argument passed to the method is the key to check for, and
➢ The second argument is the value to set at that key if the key does not exist.
The setdefault() Method
➢ The setdefault() method returns the value of the item with the specified key.
➢ If the key does not exist, insert the key, with the specified value
➢ None if key is not in the dictionary and default_value is not specified.

➢ The first time setdefault() is called, the dictionary in spam changes to


{'color': 'black', 'age': 5, 'name': 'Pooka’}.

➢ The method returns the value 'black' because this is now the value set
for the key 'color’.

➢ When spam.setdefault('color', 'white') is called next, the value for that


key is not changed to 'white', because spam already has a key named
'color'.
Dictionaries Built-in methods
Method Description
keys() Returns a list containing the dictionary's keys
values() Returns a list of all the values in the dictionary
items() Returns a list containing a tuple for each key value pair
get() Returns the value of the specified key
setdefault() insert the key with the specified value, if the key does not exist.
Returns the value of the specified key.
update() Updates or merging {key:value} pairs from the new dictionary into
the existing dictionary, adding or replacing as needed.
copy() Returns a copy of the dictionary
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
clear() Removes all the elements from the dictionary
Pretty Printing
• a pretty useful built-in module in Python, pprint.
• pprint - Data pretty printer
• The pprint module provides a capability to “pretty-print” arbitrary
Python data structures in a well-formatted and more readable way!
• Prettyprint is the process of converting and presenting source code or
other objects in a legible and attractive way.
• A prettyprinter takes blocks of code and prints them in an pleasing
fashion, presenting the characters with line breaks and indentations
to make the code comprehensible.
• Prettyprint creates a representation of source code that can be easily
analyzed by the interpreter as well as easily read by humans.
Pretty Printing
>>> import pprint

>>> girl = {'name': 'Rose', 'age': 33, 'has_hair': True, 'hair_color': 'brown',
'height': 1.6, 'eye_color': 'brown'}
>>> pprint.pprint(girl)

Output:
{'age': 33,
'eye_color': 'brown',
'hair_color': 'brown',
'has_hair': True,
'height': 1.6,
'name': 'Rose'}
Nested Dictionary in Python

• In Python, a nested dictionary is a dictionary inside a dictionary. It's a


collection of dictionaries into one single dictionary
• Ex:
nested_dict = { 'dictA': {'key_1': 'value_1'},
'dictB': {'key_2': 'value_2’}}
• Here, the nested_dict is a nested dictionary with the dictionary dictA
and dictB. They are two dictionary each having own key and value.
Create a Nested Dictionary

• people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},


2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

• print(people)
Access elements of a Nested Dictionary

• To access element of a nested dictionary, we use indexing [] syntax in


Python
people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},
2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

• print(people[1]['name'])
• print(people[1]['age'])
• print(people[1]['sex'])
Add element to a Nested Dictionary

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},


2: {'name': 'Marie', 'age': '22', 'sex': 'Female'}}

people[3] = {}

people[3]['name'] = 'Luna'
people[3]['age'] = '24'
people[3]['sex'] = 'Female'
people[3]['married'] = 'No'

print(people[3])
Delete elements from a Nested Dictionary

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},


2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female', 'married': 'No'},
4: {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}}

del people[3]['married']
del people[4]['married']

print(people[3])
print(people[4])
Delete dictionary from a nested dictionary

people = {1: {'name': 'John', 'age': '27', 'sex': 'Male'},


2: {'name': 'Marie', 'age': '22', 'sex': 'Female'},
3: {'name': 'Luna', 'age': '24', 'sex': 'Female'},
4: {'name': 'Peter', 'age': '29', 'sex': 'Male'}}

del people[3], people[4]


print(people)
Iterating Through a Nested Dictionary
Using the for loops, we can iterate through each elements in a nested dictionary.

people = {1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'},


2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}}

for p_id, p_info in people.items():


print("\nPerson ID:", p_id)

for key in p_info:


print(key + ':', p_info[key])
• Key Points to Remember:
1.Nested dictionary is an unordered collection of dictionary
2.Slicing Nested Dictionary is not possible.
3.We can shrink or grow nested dictionary as need.
4.Like Dictionary, it also has key and value.
5.Dictionary are accessed using key.
PYTHON PROGRAMMING
Module 3 continued
Manupulating Strings
Working with Strings
Topics in String
• Escape characters
• Raw String
• Multiline Strings with Triple Quotes
• Indexing and Slicing Strings
• The in and not in Operators with Strings
• string interpolation - Putting Strings Inside Other Strings
• f-strings
Topics in String – String methods
1. upper() 11. startswith()
2. lower() 12. endswith()
13. join()
3. isupper() 14. split()
4. islower() 15. partition()
5. isalpha() 16. rjust(), ljust(), and
center()
6. isalnum()
17. strip(), rstrip(), and
7. isdecimal() lstrip() Methods
8. isspace() 18. ord() and chr()
9. istitle() 19. pyperclip Module-
copy() and paste()
Escape characters
• In Python, the backslash(\) is a special character.
• If you use the backslash in front of another character, it
changes the meaning of that character

• For example, the t is a literal character.


• But if you use the backslash character in front of the
letter t, it’ll become the tab character (\t).
• "He said, "Wow!""
Escape characters
File "<stdin>", line 1
"He said, "Wow!""
^ Escape Meaning
SyntaxError: invalid syntax Character
\’ Single quote
>>> "He said, 'Wow!'"
"He said, 'Wow!’” \” Double
quote
>>> "He said, \"Wow!\""
'He said, "Wow!“’
\n Newline

\t Tab
>>> 'That is Carol\'s cat.’)
‘That is Carol's cat.’
Raw String
• A raw string completely ignores all escape characters and
prints any backslash that appears in the string.
• Raw strings treat the backslash character (\) as a literal
character.
• place an r before the beginning quotation mark of a string to
make it a raw string.
• Ex 1:
>>> print(r'That is Carol\'s cat.’)
That is Carol\'s cat.
Raw String:
• Raw strings don't treat the backslash as a special character at all. Every
character you put into a raw string stays the way you wrote it:
>>> print 'C:\\nowhere'
This would print following result:
C:\nowhere

Ex 2:
Now let's make use of raw string. We would put expression in
r'expression' as follows:
>>> print r'C:\\nowhere'
This would print following result:
C:\\nowhere
Working with Strings

Multiline Strings with Triple Quotes

➢ While you can use the \n escape character to put a newline into a string, it is
often easier to use multiline strings.
➢ A multiline string in Python begins and ends with either three single quotes or
three double quotes.
➢ Any quotes, tabs, or newlines in between the “triple quotes” are considered
part of the string.
➢ Python’s indentation rules for blocks do not apply to lines inside a multiline
string.
Working with Strings

Multiline Strings with Triple Quotes


Working with Strings

Multiline Comments
While the hash character (#) marks the beginning of a comment for the rest of the
line, a multiline string is often used for comments that span multiple lines.
Working with Strings

Indexing and Slicing Strings


• Strings use indexes and slices the
same way lists do.
• You can think of the string 'Hello,
world!' as a list and each character in
the string as an item with a
corresponding index.
Working with Strings

The in and not in Operators with Strings


• The in and not in operators can be
used with strings just like with list
values.
• An expression with two strings
joined using in or not in will
evaluate to a Boolean True or
False.
Putting Strings Inside Other Strings
Putting strings inside other strings is a common operation in programming. So
far, we’ve been using the + operator and string concatenation to do this:

However, this requires a lot of tedious typing.


Putting Strings Inside Other Strings
➢ A simpler approach is to use string interpolation, in which the %s operator
inside the string acts as a marker to be replaced by values following the string.
➢ One benefit of string interpolation is that str() doesn’t have to be called to
convert values to strings.
Putting Strings Inside Other Strings
➢ Python 3.6 introduced f-strings, which is similar to string interpolation except
that braces are used instead of %s, with the expressions placed directly inside
the braces.
➢ Like raw strings, f-strings have an f prefix before the starting quotation mark.
Putting Strings Inside Other Strings

➢ Remember to include the f prefix; otherwise, the braces and their contents will
be a part of the string value:
Useful String Methods

String Methods Description

upper() Return a new string where all the letters in the original string
have been converted to uppercase
lower() Return a new string where all the letters in the original string
have been converted to lowercase

isupper() Return a Boolean True value if the string has at least one letter
and all the letters are uppercase otherwise returns Boolean False

islower() Return a Boolean True value if the string has at least one letter
and all the letters are lowercase otherwise returns Boolean False
Useful String Methods
The upper(), lower() Methods
➢ The upper() and lower() string methods return a new string where all the
letters in the original string have been converted to uppercase or lowercase,
respectively.
➢ Nonletter characters in the string remain unchanged.
Useful String Methods
Note:

➢ These methods do not change the string itself but return new string values.
➢ If you want to change the original string, you have to call upper() or lower()
on the string and then assign the new string to the variable where the original
was stored.
➢ This is why you must use
spam = spam.upper() to change the string in spam instead of simply
spam.upper().

(This is just like if a variable eggs contains the value 10. Writing eggs + 3 does
not change the value of eggs, but eggs = eggs + 3 does.)
Useful String Methods

➢ When you run this program, the question is displayed,


and entering a variation on great, such as GREat, will
still give the output I feel great too.
➢ Adding code to your program to handle variations or
mistakes in user input, such as inconsistent
capitalization, will make your programs easier to use
and less likely to fail.
Useful String Methods
The isupper(), and islower() Methods
➢ The isupper() and islower() methods will return a Boolean True value if the
string has at least one letter and all the letters are uppercase or lowercase,
respectively. Otherwise, the method returns Boolean False.
Useful String Methods

➢ Since the upper() and lower() string methods themselves return strings, you
can call string methods on those returned string values as well.
➢ Expressions that do this will look like a chain of method calls.
Useful String Methods

The isX() Methods


These methods return a Boolean value that describes the nature of the string.
Here are some common isX string methods:
String Methods Description
isalpha() Returns True if the string consists only of letters and isn’t blank
isalnum() Returns True if the string consists only of letters and numbers and
is not blank
isdecimal() Returns True if the string consists only of numeric characters and
is not blank
isspace() Returns True if the string consists only of spaces, tabs, and
newlines and is not blank
istitle() Returns True if the string consists only of words that begin with
an uppercase letter followed by only lowercase letters
Useful String Methods
String Methods Description
isalpha() Returns True if the string consists only of letters and isn’t blank
Useful String Methods
String Methods Description
isdecimal() Returns True if the string consists only of numeric characters and
is not blank
Useful String Methods
String Methods Description
isspace() Returns True if the string consists only of spaces, tabs, and newlines and
is not blank
Useful String Methods
String Methods Description
isalnum() Returns True if the string consists only of letters and numbers and is not blank
Useful String Methods
String Methods Description
istitle() Returns True if the string consists only of words that begin with
an uppercase letter followed by only lowercase letters
The startswith() and endswith() Methods
• The startswith() and endswith() methods return True if the string
value they are called on begins or ends (respectively) with the string
passed to the method;
• otherwise, they return False. >>> 'Hello, world!'.startswith('Hello’)
True
>>> 'Hello, world!'.endswith('world!’)
True
>>> 'abc123'.startswith('abcdef’)
False
>>> 'abc123'.endswith('12’)
False
>>> 'Hello, world!'.startswith('Hello, world!’)
True
>>> 'Hello, world!'.endswith('Hello, world!’)
True
The join() and split() Methods
• join() Method
• The join() method is useful to join the list of strings into a single string
value.
• The join() method is called on a string, gets passed a list of strings, and
returns a string.
• The returned string is the concatenation of each string in the passed-in
list.
>>> ', '.join(['cats', 'rats', 'bats’])
'cats, rats, bats’
>>> ' '.join(['My', 'name', 'is', 'Simon’])
'My name is Simon’
>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])
'MyABCnameABCisABCSimon'
The join() and split() Methods
• The split() method >>> 'My name is Simon'.split()
does the opposite of ['My', 'name', 'is', 'Simon’]
join() method
• When it is called on a
string value, it returns
a list of strings.
• a delimiter string to >>>'MyABCnameABCisABCSimon'.split('ABC’)
the split() method can ['My', 'name', 'is', 'Simon’]
be used to specify a
different string to split.
>>> 'My name is Simon'.split('m’)
['My na', 'e is Si', 'on']
Splitting Strings with the partition() Method
• The partition() method is useful for splitting a string whenever you
need the parts before, including, and after a particular separator
string.
• The partition() string method can split a string into the text before
and after a separator string.
• This method searches the string it is called on for the separator string
it is passed, and returns a tuple of three substrings for the “before,”
“separator,” and “after” substrings.

>>> 'Hello, world!'.partition('w')


('Hello, ', 'w', 'orld!’)
>>> 'Hello,world!'.partition('world')
('Hello, ', 'world', '!')
• If the separator string you pass to >>> 'Hello, world!'.partition('o’)
partition() occurs multiple times in
the string that partition() calls on, ('Hell', 'o', ', world!’)
the method splits the string only on
the first occurrence
• If the separator string can’t be >>> 'Hello, world!'.partition('XYZ’)
found, the first string returned in
the tuple will be the entire string, ('Hello, world!', '', '')
and the other two strings will be
empty
• The multiple assignment trick to >>> before, sep, after = 'Hello, world!'.partition(‘ ')
assign the three returned strings to >>> before
three variables 'Hello,’
>>> after
'world!'
Justifying Text with the rjust(), ljust(), and center()
Methods
• rjust(), ljust(), and center() lets you ensure that strings are neatly
aligned
• The rjust() and ljust() string methods return a padded version of the
string they are called on, with spaces inserted to justify the text.
• The first argument to both methods is an integer length for the
justified string. >>> 'Hello'.rjust(10)
‘ Hello’
>>> 'Hello'.rjust(20)
‘ Hello’
>>> 'Hello, World'.rjust(20)
‘ Hello, World’
>>> 'Hello'.ljust(10)
'Hello ’
• An optional second argument to >>> 'Hello'.rjust(20, '*')
rjust() and ljust() will specify a '***************Hello’
fill character other than a space >>> 'Hello'.ljust(20, '-’)
character.
'Hello---------------'

• The center() string method >>> 'Hello'.center(20)


works like ljust() and rjust() but ‘ Hello ‘
centers the text rather than
justifying it to the left or right.
>>> 'Hello'.center(20, '=')
'=======Hello========'
Removing Whitespace with the strip(), rstrip(), and
lstrip() Methods
• To strip off whitespace characters >>> spam = ' Hello, World ‘
(space, tab, and newline) from >>> spam.strip()
the left side, right side, or both
sides of a string 'Hello, World’
• The strip() string method will
return a new string without any
whitespace characters at the
beginning or end. >>> spam.lstrip()
• The lstrip() and rstrip() methods 'Hello, World ‘
will remove whitespace >>> spam.rstrip()
characters from the left and right
ends, respectively. ‘ Hello, World'
Numeric Values of Characters with the
ord() and chr() Functions
• Computers store information as bytes—strings of binary numbers,
which means we need to be able to convert text to numbers.
• Because of this, every text character has a corresponding numeric
value called a Unicode code point.
• For example, the numeric code point is 65 for 'A', 52 for '4', and 33 for
'!’.
• The ord() function to get the code point of a one-character string
• The chr() function to get the one-character string of an integer code
point.
Examples - ord() and chr() Functions
>>> ord('A’) >>> ord('B’)
65 66
>>> ord('4’) >>> ord('A') < ord('B')
52 True
>>> ord('!’) >>> chr(ord('A’))
33 'A’
>>> chr(65) >>> chr(ord('A') + 1)
'A' 'B'
Copying and Pasting Strings with the
pyperclip Module
• The pyperclip module has copy() and paste() functions that can send
text to and receive text from your computer’s clipboard.
• The pyperclip module does not come with Python. To install it as a
third-party module.
• Install it by running the following command in your command
prompt or terminal:
pip install pyperclip >>> import pyperclip
>>> pyperclip.copy('Hello, world!’)
>>> pyperclip.paste()
'Hello, world!'
Thank You

You might also like