0% found this document useful (0 votes)
10 views73 pages

1.2.1 Data Types and Operations

Uploaded by

Saravana Priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views73 pages

1.2.1 Data Types and Operations

Uploaded by

Saravana Priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 73

Data Types and Operations

Operation in Data types


• Strings
– Slicing
– Modify
– Concatenate
– Format
– Escape Characters
– String methods
Slicing strings
• You can return a range of characters by using the slice
syntax.
• Specify the start index and the end index, separated
by a colon, to return a part of the string.
Example
Get the characters from position 2 to position 5 (not
included):
b = "Hello, World!"
print(b[2:5])
Output: llo
Slicing strings
Slice From the Start – prints all the characters by leaving out the last
index, the range will start at the first character:
Example: Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
Output: Hello

Slice To the End - By leaving out the start index, the range will go to
the end:
Example: Get the characters from position 2, and all the way to the
end:
b = "Hello, World!"
print(b[2:])
Output: llo, World!
Slicing strings
Negative Indexing - Use negative indexes to
start the slice from the end of the string:
Example: Get the characters: From: "o" in
"World!" (position -5) To, but not included: "d"
in "World!" (position -2):
b = "Hello, World!"
print(b[-5:-2])
Output: orl
Modify Strings
• Python has a set of built-in methods that you can use on strings.
Upper Case
Example: The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
Output: HELLO, WORLD!

Lower Case
Example: The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Output: hello, world!
Modify Strings
Remove Whitespace
• Whitespace is the space before and/or after the actual text, and very
often you want to remove this space.
• The strip() method removes any whitespace from the beginning or the
end:
Ex:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!“

Replace String
• The replace() method replaces a string with another string:
Ex:
a = "Hello, World!"
print(a.replace("H", "J")) #returns “Jello, World!”
Modify Strings
Split String
• The split() method returns a list where the text between the
specified separator becomes the list items.
• It splits the string into substrings if it finds instances of the
separator:
Example
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
String Concatenation
• To concatenate, or combine, two strings you can use the + operator.
Merge variable a with variable b into variable c:
Ex.
a = "Hello"
b = "World"
c=a+b
print(c)
Output: HelloWorld
• To add a space between them, add a " ":
Ex.
a = "Hello"
b = "World"
c=a+""+b
print(c)
Output: Hello World
String Format
• We cannot combine strings and numbers like this:
age = 36
txt = "My name is John, I am " + age
print(txt)
• This will throw an error like..
Traceback (most recent call last):
File "demo_string_format_error.py", line 2, in <module>
txt = "My name is John, I am " + age
TypeError: must be str, not int
• But we can combine strings and numbers by using the format() method.
The format() method takes the passed arguments, formats them, and
places them in the string where the placeholders {} are.
age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))
Output: My name is John, and I am 36
Escape Characters
• To insert characters that are illegal in a string, use an escape
character.
• An escape character is a backslash \ followed by the character
you want to insert.
• An example of an illegal character is a double quote inside a
string that is surrounded by double quotes:
Example
• You will get an error if you use double quotes inside a string that
is surrounded by double quotes:
• txt = "We are the so-called "Vikings" from the north.“
File "demo_string_escape_error.py", line 1
txt = "We are the so-called "Vikings" from the north."
^
SyntaxError: invalid syntax
Escape Characters
• To fix this problem, use the escape character \":
• Example
• The escape character allows you to use double
quotes when you normally would not be allowed:
• txt = "We are the so-called \"Vikings\" from the
north."
Other escape characters used in Python:
Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
\ooo Octal value
\xhh Hex value
String Methods
Capitalize() Method
• The capitalize() method returns a string where the first
character is upper case, and the rest is lower case.
• Syntax: string.capitalize()
Upper case the first letter in this sentence:
txt = "hello, and welcome to my world."
Ex.
x = txt.capitalize()
print (x)
Output: Hello, and welcome to my world.
Ex.
txt = "python is FUN!"
x = txt.capitalize()
print (x)
Output: Python is fun!
Operation in List data type
• Access list items
• Remove List Items
• Loop Lists
• List Comprehension
• Sort Lists
• Copy Lists
• Join Lists
• List Methods
List
Access Items: List items are indexed and you can
access them by referring to the index number:
• Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1]) Output: banana

Negative Indexing: start from the end, -1 refers to


the last item, -2 refers to the second last item etc.
Example: Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1]) Output: cherry
• Range of Indexes: You can specify a range of indexes by specifying
where to start and where to end the range. When specifying a range,
the return value will be a new list with the specified items.
Example: Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5]) Output: [cherry", "orange", "kiwi]
By leaving out the start value, the range will start at the first item:
• This example returns the items from the beginning to, but NOT
including, "kiwi":
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4]) Output: ["apple", "banana", "cherry", "orange“]
By leaving out the end value, the range will go on to the end of the list:
• This example returns the items from "cherry" to the end:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:]) output: ["cherry", "orange", "kiwi", "melon", "mango"]
Range of Negative Indexes: Specify negative indexes if you want to start
the search from the end of the list:
This example returns the items from "orange" (-4) to, but NOT including
"mango" (-1):
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Output:
[“orange", "kiwi", "melon”]

Check if Item Exists: To determine if a specified item is present in a list


use the in keyword:
Example: Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Output : Yes, 'apple' is in the fruits list
• Change Item Value: To change the value of a specific item, refer to the index number:
Example: Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist) Output: ["apple", " blackcurrant ", "cherry"]

• Change a Range of Item Values: To change the value of items within a specific range,
define a list with the new values, and refer to the range of index numbers where you
want to insert the new values:
Example: Change the values "banana" and "cherry" with the values "blackcurrant" and
"watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
Output: ["apple", " blackcurrant ", " watermelon", "orange", "kiwi", "mango"]

• If you insert more items than you replace, the new items will be inserted where you
specified, and the remaining items will move accordingly:
Example: Change the second value by replacing it with two new values:
thislist = ["apple", "banana", "cherry"]
thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist) Output: ["apple", " blackcurrant ", " watermelon", " cherry “]
• The length of the list will change when the number of items
inserted does not match the number of items replaced.
• If you insert less items than you replace, the new items will be
inserted where you specified, and the remaining items will move
accordingly:
• Example: Change the second and third value by replacing it
with one value:
thislist = ["apple", "banana", "cherry"]
thislist[1:3] = ["watermelon"]
print(thislist) Output: ["apple", " watermelon”]
• To insert a new list item, without replacing any of the existing
values, we can use the insert() method. The insert() method
inserts an item at the specified index:
• Example: Insert "watermelon" as the third item:
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist) Output: ["apple", "banana", ”watermenlon”, "cherry"]
Add List Items
• Append Items: To add an item to the end of the list, use
the append() method:
Example: Using the append() method to append an item
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist) Output: ["apple", "banana", "cherry“, orange]
• Insert Items: To insert a list item at a specified index, use
the insert() method. The insert() method inserts an item at
the specified index:
Example: Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist) Output: ["apple", ” orange “, "banana", "cherry“]
Add List Items
• Extend List: To append elements from another list to the current list,
use the extend() method.
Example: Add the elements of tropical to thislist:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
Output: ['apple', 'banana', 'cherry', 'mango', 'pineapple', 'papaya']
The elements will be added to the end of the list.
• Add Any Iterable: The extend() method does not have to append lists,
you can add any iterable object (tuples, sets, dictionaries etc.).
Example: Add elements of a tuple to a list:
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)
Output: ['apple', 'banana', 'cherry', 'kiwi', 'orange']
Remove List Items
Remove Specified Item: The remove() method removes the
specified item.
Example: Remove "banana":
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Output: ["apple", "cherry"]
• If there are more than one item with the specified value,
the remove() method removes the first occurance
Example: Remove the first occurance of "banana":
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("banana")
print(thislist)
Output: ["apple", "cherry", "banana", "kiwi"]
Remove Specified Index: The pop() method removes
the specified index.
Example: Remove the second item:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
Output: ["apple", "cherry"]
If you do not specify the index, the pop() method
removes the last item.
• Example: Remove the last item:
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist) output: [‘apple’, ‘banana’]
• The del keyword also removes the specified index
Example: Remove the first item:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
Output: ["banana", "cherry"]

• The del keyword can also delete the list completely.


Example: Delete the entire list:
thislist = ["apple", "banana", "cherry"]
del thislist #this will cause an error because you have
succsesfully deleted "thislist".
• Clear the List: The clear() method empties the
list. The list still remains, but it has no content.
Example: Clear the list content:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
sort() Method
• Sort the list alphabetically.
• The sort() method sorts the list
ascending by default.
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
Output: ['Volvo', 'Ford', 'BMW’]
• You can also make a function to decide
the sorting criteria(s).
list.sort(reverse=True|False,
key=myFunc)
Parameter Description
reverse Optional. reverse=True will sort the list
descending. Default is reverse=False
key Optional. A function to specify the sorting
criteria(s)

Sort the list descending:


cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
print(cars)
Output: ['Volvo', 'Ford', 'BMW']
• Sort the list by the length of the values:
• # A function that returns the length of the
value:
def myFunc(e):
return len(e)
cars=['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
print(cars)
Output:['VW', 'BMW', 'Ford', 'Mitsubishi’]
• Sort a list of dictionaries based on the "year" value of
the dictionaries:
# A function that returns the 'year' value:
def myFunc(e):
return e['year']
cars = [
{'car': 'Ford', 'year': 2005},
{'car': 'Mitsubishi', 'year': 2000},
{'car': 'BMW', 'year': 2019},
{'car': 'VW', 'year': 2011}
]
cars.sort(key=myFunc)
print(cars)
[{'car': 'Mitsubishi', 'year': 2000}, {'car':
'Ford', 'year': 2005}, {'car': 'VW', 'year':
2011}, {'car': 'BMW', 'year': 2019}]
• Sort the list by the length of the
values and reversed:
• # A function that returns the length
of the value:
def myFunc(e):
return len(e)
cars =
['Ford', 'Mitsubishi', 'BMW', 'VW']
cars.sort(reverse=True, key=myFunc)
Operations on Tuples
• Update Tuples
• Unpack Tuples
• Loop Tuples
• Join Tuples
• Tuple Methods
Update Tuples

• Change Tuple Values: Once a tuple is created, you


cannot change its values. Tuples are unchangeable,
or immutable as it also is called.
• But, you can convert the tuple into a list, change the
list, and convert the list back into a tuple.
• Example:Convert the tuple into a list to be able to
change it:
• x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)
Add Items
Since tuples are immutable, they do not have a
built-in append() method, but there are other
ways to add items to a tuple.
1. Convert into a list: Just like the workaround
for changing a tuple, you can convert it into a list,
add your item(s), and convert it back into a tuple.
Example: Convert the tuple into a list, add
"orange", and convert it back into a tuple:
thistuple = ("apple", "banana", "cherry")
y = list(thistuple)
y.append("orange")
thistuple = tuple(y)
2. Add tuple to a tuple. You are allowed to
add tuples to tuples, so if you want to add one
item, (or many), create a new tuple with the
item(s), and add it to the existing tuple:
Example: Create a new tuple with the value
"orange", and add that tuple:
thistuple =
("apple", "banana", "cherry")
y = ("orange",)
thistuple += y
print(thistuple)
Unpack Tuples
• When we create a tuple, we normally assign values to
it. This is called "packing" a tuple:
• Example: Packing a tuple:
fruits = ("apple", "banana", "cherry")

• But, in Python, we are also allowed to extract the


values back into variables. This is called "unpacking":

• Example: Unpacking a tuple:


fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)
print(yellow)
print(red)
Using Asterisk*
• The number of variables must match the number of
values in the tuple, if not, you must use an asterisk to
collect the remaining values as a list.
• Assign the rest of the values as a list called "red":
fruits=("apple", "banana", "cherry", "strawberry
", "raspberry")
(green, yellow, *red) = fruits
print(green)
print(yellow)
print(red)
• If the asterisk is added to another variable name than
the last, Python will assign values to the variable until
the number of values left matches the number of
variables left.
• Add a list of values the "tropic" variable:
• fruits =
("apple", "mango", "papaya", "pine
apple", "cherry")

(green, *tropic, red) = fruits

print(green)
print(tropic)
print(red)
Loop Tuples
• Loop Through a Tuple
Iterate through the items and print the values:
thistuple =
("apple", "banana", "cherry")
for x in thistuple:
print(x)
• Loop Through the Index Numbers
You can also loop through the tuple items by
referring to their index number.
Use the range() and len() functions to
create a suitable iterable.
• Print all items by referring to their
index number:
• thistuple =
("apple", "banana", "cherry")
for i in range(len(thistuple)):
print(thistuple[i])
Using a While Loop
You can loop through the tuple items by using
a while loop.
Use the len() function to determine the length of the
tuple, then start at 0 and loop your way through the
tuple items by referring to their indexes.
Remember to increase the index by 1 after each
iteration.
Print all items, using a while loop to go through
all the index numbers:
thistuple = ("apple", "banana", "cherry")
i = 0
while i < len(thistuple):
print(thistuple[i])
i = i + 1
Join Two Tuples
To join two or more tuples you can use the + operator:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)

Multiply Tuples: If you want to multiply the content of a


tuple a given number of times, you can use
the * operator:

Example:Multiply the fruits tuple by 2:


fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
count() Method
The count() method returns the number of times a
specified value appears in the tuple.

Syntax
tuple.count(value)

Example: Return the number of times the value 5


appears in the tuple
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.count(5)
print(x)
Output: 2
Operations on Set data type
• Access set items
• Add Set Items
• Remove Set Items
• Loop Sets
• Join Sets
• Set Methods
Access set items
• You cannot access items in a set by referring to an
index or a key.
• But you can loop through the set items using
a for loop, or ask if a specified value is present in a
set, by using the in keyword.

Example: Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}


for x in thisset:
print(x)

Output:
Apple
Banana
Cherry
Check if "banana" is present in the set:
• thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)
• Once a set is created, you cannot change its items,
but you can add new items.
Add Set Items

Add Items: Once a set is created, you cannot change its


items, but you can add new items. To add one item to a
set use the add() method.
Example: Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Output: {"apple", "banana", "cherry“,
“orange"}

Add Sets: To add items from another set into the


current set, use the update() method.
Example: Add elements from tropical into thisset
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset) Output:
Add Any Iterable: The object in the update() method
does not have to be a set, it can be any iterable object
(tuples, lists, dictionaries etc.).

Example: Add elements of a list to at set:

thisset = {"apple", "banana", "cherry"}


mylist = ["kiwi", "orange"]
thisset.update(mylist)
print(thisset)
Output:{'banana', 'cherry', 'apple',
'orange','kiwi'}
Remove Set Items
• Remove Item: To remove an item in a set, use
the remove(), or the discard() method.

Example: Remove "banana" by using remove() method:

thisset ={"apple", "banana", "cherry"}


thisset.remove("banana")
print(thisset) Output: {"apple", "cherry"}

If the item to remove does not exist, remove() will raise


an error.
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
If the item to remove does not
exist, discard() will NOT raise an error.
You can also use the pop() method to remove an item, but
this method will remove a random item, so you cannot be
sure what item that gets removed. Sets are unordered, so
when using the pop() method, you do not know which
item that gets removed. The return value of
the pop() method is the removed item.

Remove a random item by using the pop() method:


thisset = {"apple", "banana", "cherry"}
x = thisset.pop()
print(x)
print(thisset) output: apple, {“banana”,
“cherry”}
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
thisset.clear()
print(thisset)
Output: set()
The del keyword will delete the set
completely:
thisset =
{"apple", "banana", "cherry"}

del thisset

print(thisset)
Loop Sets
• You can loop through the set items by using
a for loop:

Example: Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}


for x in thisset:
print(x)

Output:
apple
banana
cherry
Join sets
• Join Two Sets: there are several ways to join two or more sets in
Python. You can use the union() method that returns a new
set containing all items from both sets, or update() method
that inserts all the items from one set into another

• The union() method returns a new set with all items from both
sets:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3) Output: {1, 'c', 'a', 2, 3, 'b'}

• The update() method inserts the items in set2 into set1:


set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1) Output: {3, 2, 'b', 'a', 'c', 1}

• Both union() and update() will exclude any duplicate items.


Keep ONLY the Duplicates
The intersection_update() method will keep only the
items that are present in both sets.
Example: Keep the items that exist in both set x, and
set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.intersection_update(y)
print(x)

The intersection() method will return a new set, that


only contains the items that are present in both sets.
Example: Return a set that contains the items that exist in
both set x, and set y:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.intersection(y)
print(z)
Keep All, But NOT the Duplicates
The symmetric_difference_update() method will keep only the
elements that are NOT present in both sets.
Example: Keep the items that are not present in both sets:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
x.symmetric_difference_update(y)
print(x)

The symmetric_difference() method will return a new set, that


contains only the elements that are NOT present in both sets.
• Example: Return a set that contains all items from both sets,
except items that are present in both:
• x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
z = x.symmetric_difference(y)
print(z)
True and 1 is considered the same value:
x =
{"apple", "banana", "cherry", True}
y = {"google", 1, "apple", 2}

z = x.symmetric_difference(y)

Output: {2, 'google', 'cherry',


'banana'}
Operations on Dictionary Datatype
• Access Items
• Change Items
• Add Items
• Remove Items
• Loop Dictionaries
• Copy Dictionaries
• Nested Dictionaries
• Dictionary Methods
Accessing Items
• You can access the items of a dictionary by referring to
its key name, inside square brackets:
• Get the value of the "model" key:
• thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]

• There is also a method called get() that will give you


the same result:
• Get the value of the "model" key:
• x = thisdict.get("model")
Get Keys: The keys() method will return
a list of all the keys in the dictionary.
Get a list of the keys:
x = thisdict.keys()

The list of the keys is a view of the


dictionary, meaning that any changes
done to the dictionary will be reflected
in the keys list.
• Add a new item to the original dictionary, and see that the keys list
gets updated as well:
• car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.keys()

print(x) #before the change

car["color"] = "white"

print(x) #after the change


Get Values
The values() method will return a list of all the values in the
dictionary.

Get a list of the values:


x = thisdict.values()

The list of the values is a view of the dictionary, meaning that any
changes done to the dictionary will be reflected in the values list.

• Make a change in the original dictionary, and see that the


values list gets updated as well:
• car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
print(x) #after the change
The items() method will return each item in a dictionary,
as tuples in a list.

Example: Get a list of the key:value pairs


x = thisdict.items()

• Check if "model" is present in the dictionary:


• thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in
the thisdict dictionary")
Change Values
• You can change the value of a
specific item by referring to its key
name:
• Change the "year" to 2018:
• thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Update Dictionary

he update() method will update the dictionary with the


items from the given argument.
The argument must be a dictionary, or an iterable object
with key:value pairs.

Example
Update the "year" of the car by using
the update() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})
Removing Items
There are several methods to remove items from a dictionary:
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

The popitem() method removes the last inserted item (in versions
before 3.7, a random item is removed instead):
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)

The del keyword can also delete the dictionary completely:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because
"thisdict" no longer exists.
The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.clear()
print(thisdict)
Loop Dictionaries
• Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
• Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
• You can also use the values() method to return values of a
dictionary:
for x in thisdict.values():
print(x)
• You can use the keys() method to return the keys of a
dictionary:
for x in thisdict.keys():
print(x)
• Loop through both keys and values, by using
the items() method:
for x, y in thisdict.items():
print(x, y)
Copy a Dictionary
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)

Make a copy of a dictionary with the dict() function:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)
Nested Dictionaries
• A dictionary can contain dictionaries, this is called nested
dictionaries.
• Create a dictionary that contain three dictionaries:
• myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
• Create three dictionaries, then create one dictionary that will
contain the other three dictionaries:
• child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}

myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
Access Items in Nested Dictionaries

• To access items from a nested dictionary, you use the


name of the dictionaries, starting with the outer
dictionary:
• Example Print the name of child 2:
print(myfamily["child2"]["name"])
END OF CHAPTER 1.2

You might also like