Python Part 3
Python Part 3
1. Python Collection
2. List, Length, Constructor
3. Indexing in List, Access items with range Indexes
4. Insert, Append, Extend, Remove Items, Clear List
5. Access items of list using loop- for loop, while loop,
6. Looping Using List Comprehension
7. Sort, Reverse, Copy, Join and Count Operations
8. Tuple, Length, Constructor
9. Indexing in Tuples, Access items of Tuples via range indexing
10. Add, update and Remove items of Tuple, Unpacking of Tuple
11. Access items of Tuple via for and while loop
12. Join, Count and Multiply operations on Tuple
13. Sets, Length, Constructor
14. Access items of set via for loop
15. Add items, Add sets, Add any iterable, Remove item, Clear items of set, Delete set
16. Join set, Join Multiple set, Join set with tuple
17. Intersection, Difference, Symmetric difference operations on set
18. Dictionary, Length, Constructor
19. Access items of Dictionary , get(), keys(), values(), items() method
20. Add, Update, Remove items and values of Dictionary
21. Access items , values or both from Dictionary
22. Nested Dictionary
Python Collections (Arrays)
There are four collection data types in the Python programming language –
List is a collection which is ordered, indexed and changeable. Allows duplicate members.
*Set items are unchangeable, but you can remove and/or add items whenever you like.
**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries
are unordered.
When choosing a collection type, it is useful to understand the properties of that type.
Choosing the right type for a particular data set could mean retention of meaning, and, it
could mean an increase in efficiency or security.
Python Lists
Lists are used to store multiple items in a single variable.
Lists are created using square brackets.
List items are ordered, indexed, changeable, and allow duplicate values.
List Length
To determine how many items a list has, use the len() function. Example -
mylist = ["a", "b", "c"]
print(len(mylist))
List items can be of any data type: Example -
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
A list can contain different data types: Example -
list1 = ["abc", 34, True, 40, "male"]
lists are defined as objects with the data type 'list': <class 'list'>
Example-
mylist = [10,20,30]
print(type(mylist))
The list() Constructor
It is also possible to use the list() constructor when creating a new list.
mylist = list((10,20,30)) # note the double round-brackets
print(mylist)
Access Items
List items are indexed and you can access them by referring to the index number.
Negative Indexing
Negative indexing means start from the end
-1 refers to the last item, -2 refers to the second last item etc.
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 -
mylist = [10,20,30,40,50,60,70,80]
print(mylist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not included).
By leaving out the start value, the range will start at the first item.
print(mylist[:5])
By leaving out the end value, the range will go on to the end of the list.
print(mylist[2:])
Range of Negative Indexes
Specify negative indexes if we want to start the search from the end of the list.
print(mylist[-5:-1])
Check if Item Exists
To determine if a specified item is present in a list use the in keyword.
Ex. if 10 in mylist :
Change Item Value
To change the value of a specific item, refer to the index number.
Ex. mylist[1] =50
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 we want to insert the new values.
Ex. mylist[1:3] =[60,70]
If we insert more items than we replace, the new items will be inserted where we
specified, and the remaining items will move accordingly.
Ex. mylist[1:2] =[60,70]
Note: The length of the list will change when the number of items inserted does not
match the number of items replaced.
If we insert less items than we replace, the new items will be inserted where we specified,
and the remaining items will move accordingly. Example-
mylist = [10,20,30,40,50]
mylist[1:3] = [90]
print(mylist) # Output - [10, 90, 40, 50]
Insert Items
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: Ex.
[Link](2, 90)
Append Items
To add an item to the end of the list, use the append() method: Ex.
[Link](80)
Extend List
To append elements from another list to the current list, use the extend() method. Ex.
list1 = [10,20,30]
list2 = [40,50]
[Link](list2)
print(list1)
The elements will be added to the end of the list.
Add Any Iterable
By using extend() method does not have to append lists, you can add any iterable object
(tuples, sets, dictionaries etc.). Ex.
list1 = [10,20,30] # This is list
list2 = (40,50) # This is tuple
[Link](list2)
print(list1) # Output - [10, 20, 30, 40, 50]
Remove List Items
The remove() method removes the specified item. Ex.
[Link](90)
If there are more than one item with the specified value, the remove() method removes the
first occurrence.
Remove Specified Index
The pop() method removes the specified index. Ex. [Link](2)
If you do not specify the index, the pop() method removes the last item. Ex. [Link]()
The del keyword also removes the specified index: Ex. del mylist[2]
The del keyword can also delete the list completely. Ex. del mylist
Clear the List
The clear() method empties the list.
The list still remains, but it has no content. Ex. [Link]()
Loop Through a List - We can loop through the list items by using a for loop: Ex.
mylist = [10,20,30,40,50]
for x in mylist:
print(x)
Loop Through the Index Numbers
We can also loop through the list items by referring to their index number.
Use the range() and len() functions to create a suitable iterable.
mylist = [10,20,30,40,50]
for i in range(len(mylist)):
print(mylist[i])
Using a While Loop - We can loop through the list items by using a while loop.
mylist = [10,20,30,40,50]
i=0
while i<len(mylist):
print(mylist[i])
i=i+1
Looping Using List Comprehension
List Comprehension offers the shortest syntax for looping through lists: Example-
mylist = [10,20,30,40,50]
[print(x) for x in mylist] # A short hand for loop that will print all items in a list
Based on a list of fruits, we want a new list, containing only the fruits with the letter "a"
in the name. Example-
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist) # Output - ['apple', 'banana', 'mango']
Example - Only accept items that are not "apple":
newlist = [x for x in fruits if x != "apple"]
Iterable
The iterable can be any iterable object, like a list, tuple, set etc. Example -
We can use the range() function to create an iterable:
newlist = [x for x in range(10)]
Example - Accept only numbers lower than 5:
newlist = [x for x in range(10) if x < 5]
Example - Set the values in the new list to upper case:
newlist = [[Link]() for x in fruits]
Example - Set all values in the new list to 'hello':
newlist = ['hello' for x in fruits]
Example - Return "orange" instead of "banana":
newlist = [x if x != "banana" else "orange" for x in fruits]
"Return the item if it is not banana, if it is banana return orange".
Sort List Alphanumerically
List objects have sort() method that will sort the list alphanumerically, ascending by default:
mylist = [90,20,70,40,50,80]
[Link]()
print(mylist)
Sort Descending
To sort descending, use the keyword argument reverse = True: Ex.
[Link](reverse = True)
By default the sort() method is case sensitive, resulting in all capital letters being sorted
before lower case letters.
if we want a case-insensitive sort function, use [Link] as a key function: Example -
thislist = ["banana", "Orange", "Kiwi", "cherry"]
[Link](key = [Link])
print(thislist)
Reverse Order
if we want to reverse the order of a list, regardless of the alphabet , the reverse() method
reverses the current sorting order of the elements.
thislist = ["banana", "Orange", "Kiwi", "cherry"]
[Link]()
print(thislist)
Copy a List
We cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy(). Ex.
list1 = [90,20,70,40,50,80]
list2 = [Link]()
print(list2)
Another way to make a copy is to use the built-in method list().
list1 = [90,20,70,40,50,80]
list2 = list(list1)
print(list2)
Join Two Lists
There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator. Example -
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Another way to join two lists is by appending all the items from list2 into list1, one by one.
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
[Link](x)
print(list1)
We can use the extend() method, where the purpose is to add elements from one list to
another list: Example -
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
[Link](list2)
print(list1)
List count() Method
The count() method returns the number of times the particular value appears in the list.
points = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x = [Link](9)
Python Tuples
Tuples are used to store multiple items in a single variable.
A tuple is a collection which is ordered, indexed , unchangeable and allow duplicate values.
Tuples are written with round brackets. Example-
mytuple = (20,30,40,50)
print(mytuple)
Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.
Tuple Length
To determine how many items a tuple has, use the len() function:
Ex. print(len(mytuple))
Create Tuple With One Item
To create a tuple with only one item, you have to add a comma after the item, otherwise
Python will not recognize it as a tuple. Ex. mytuple = ("apple",)
Data Types of Tuple Items
Tuple items can be of any data type, i.e. String, int and boolean data types.
A tuple can contain different data types: Ex.
tuple1 = ("abc", 34, True, 40, "male")
We can find out data type of a tuple by using type() function.
Ex. print(type(mytuple)) # output is <class 'tuple'>
From Python's perspective, tuples are defined as objects of class 'tuple‘.
The tuple() Constructor
It is also possible to use the tuple() constructor to make a tuple.
Ex. mytuple = tuple((10,20,30)) # note the double round-brackets
Access Tuple Items
We can access tuple items by referring to the index number, inside square brackets.
Negative Indexing
Negative indexing means start from the end.
-1 refers to the last item, -2 refers to the second last item etc.
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 tuple with the specified
items.
By leaving out the start value, the range will start at the first item.
By leaving out the end value, the range will go on to the end of the tuple.
Check if Item Exists
To determine if a specified item is present in a tuple use the in keyword.
Update Tuples
Tuples are unchangeable or immutable , meaning that you cannot change, add, or
remove items once the tuple is created. But we 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 = (10 , 20 , 30)
y = list(x)
y[1] = 50
x = tuple(y)
print(x)
Add Items
Since tuples are immutable, they do not have a built-in append() method but we can
convert it into a list, add item(s), and convert it back into a tuple.
Add tuple to a tuple
We are allowed to add tuples to tuples, so if we want to add one item, (or many), create a
new tuple with the item(s), and add it to the existing tuple.
mytuple = (10,20,30)
y = (40,)
mytuple += y
print(mytuple)
Remove Items
Tuples are unchangeable, so we cannot remove items from it, but we can Convert the
tuple into a list, remove item, and convert it back into a tuple.
We can delete the tuple completely by using The del keyword. Ex. del mytuple
Unpacking a Tuple
When we create a tuple, we normally assign values to it. This is called "packing" a tuple:
But, in Python, we are also allowed to extract the values back into variables. This is called
"unpacking“. Example -
mytuple = (10,20,30) # This is packing
(a, b, c) = mytuple # This is unpacking
print(a, b, c)
Using Asterisk*
If the number of variables is less than the number of values, we can add an * to the last
variable name and the values will be assigned to the variable as a list: Example-
mytuple = (10,20,30,40,50)
(a,b,*c) = mytuple
print(a,b,c) # Output- 10 20 [30, 40, 50]
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.
mytuple = (10,20,30,40,50)
(a,*b,c) = mytuple
print(a,b,c) # Output - 10 [20, 30, 40] 50
Loop Through a Tuple
We can loop through the tuple items by using a for loop.
mytuple = (10,20,30)
for x in mytuple:
print(x)
Loop Through the Index Numbers
Use the range() and len() functions to create a suitable iterable. Example -
mytuple = (10,20,30)
for i in range(len(mytuple)):
print(mytuple[i])
Using a While Loop
We can loop through the tuple items by using a while loop. Example -
mytuple = (10,20,30)
i=0
while i<len(mytuple):
print(mytuple[i])
i=i+1 Join Two Tuples
To join two or more tuples you can use the + operator. Example -
Join two tuples:
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 -
fruits = ("apple", "banana", "cherry")
mytuple = fruits * 2
print(mytuple)
Tuple count() Method
The count() method returns the number of times a specified value appears in the tuple. Ex
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = [Link](5)
print(x)
Python Sets
Sets are used to store multiple items in a single variable.
Sets are written with curly brackets.
A set is a collection which is unordered, unchangeable*, unindexed and do not allow
duplicate values. They cannot be referred to by index or key.
• Note: Set items are unchangeable, but you can remove items and add new items.
• Sets are unordered, so you cannot be sure in which order the items will appear.
Duplicate values will be ignored: Example -
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset) # Output - {'banana', 'cherry', 'apple'}
Note: The values True and 1 are considered the same value in sets, and are treated as
duplicates: Example –
thisset = {"apple", "banana", "cherry", True, 1, 2}
print(thisset) # Output- {True, 2, 'banana', 'cherry', 'apple'}
Note: The values False and 0 are considered the same value in sets, and are treated as
duplicates
Length of a Set
To determine how many items a set has, use the len() function.
Ex. print(len(thisset))
Set Items - Data Types
Set items can be of any data type. Example -
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}
A set can contain different data types. Example -
A set with strings, integers and boolean values:
set1 = {"abc", 34, True, 40, "male"}
type()
From Python's perspective, sets are defined as objects with the data type 'set':
<class 'set'>
Ex. print(type(myset))
The set() Constructor
It is also possible to use the set() constructor to make a set. Example -
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)
Access Items
We cannot access items in a set by referring to an index or a key.
But we 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.
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
print("banana" in thisset)
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-
thisset = {"apple", "banana", "cherry"}
[Link]("orange")
print(thisset)
Add Sets
To add items from another set into the current set, use the update() method.
set1 = {10,20,30}
set2 = {40,50,60}
[Link](set2)
print(set1)
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.).
myset = {10,20,30}
mylist = [40,50,60]
[Link](mylist)
print(myset)
Remove Item
To remove an item in a set, use the remove(), or the discard() method. Example -
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset) # If the item to remove does not exist, remove() will raise an error
Remove "banana" by using the discard() method:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)
Note: If the item to remove does not exist, discard() will NOT raise an error
We can also use the pop() method to remove an item, but this method will remove a
random item, so we cannot be sure what item that gets removed.
The return value of the pop() method is the removed item. Example -
thisset = {"apple", "banana", "cherry"}
x = [Link]()
print(x)
print(thisset)
Note: Sets are unordered, so when using the pop() method, you do not know which item
that gets removed.
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
[Link]()
print(thisset)
The del keyword will delete the set completely:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
Join Sets
There are several ways to join two or more sets in Python.
The union() and update() methods joins all items from both sets.
The intersection() method keeps ONLY the duplicates.
The difference() method keeps the items from the first set that are not in the other set(s).
The symmetric_difference() method keeps all items EXCEPT the duplicates.
The union() method returns a new set with all items from both sets.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = [Link](set2)
print(set3)
We can use the | operator instead of the union() method, and you will get the same result.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = set1 | set2
print(set3) Join Multiple Sets
All the joining methods and operators can be used to join multiple sets.
When using a method, just add more sets in the parentheses, separated by commas.
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = {"John", "Elena"}
set4 = {"apple", "bananas", "cherry"}
myset = [Link](set2, set3, set4)
print(myset)
Use | to join more than one sets:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = {"John", "Elena"}
set4 = {"apple", "bananas", "cherry"}
myset = set1 | set2 | set3 |set4
print(myset)
Join a Set and a Tuple
The union() method allows you to join a set with other data types, like lists or tuples.
The result will be a set. Example -
Join a set with a tuple:
x = {"a", "b", "c"}
y = (1, 2, 3)
z = [Link](y)
print(z)
Note: The | operator only allows you to join sets with sets, and not with other data types
like you can with the union() method
The update() method inserts all items from one set into another.
The update() changes the original set, and does not return a new set. Example -
The update() method inserts the items in set2 into set1:
set1 = {"a", "b" , "c"}
set2 = {1, 2, 3}
[Link](set2)
print(set1) # Note: Both union() and update() will exclude any duplicate items.
Intersection
Keep ONLY the duplicates
The intersection() method will return a new set, that only contains the items that are
present in both sets. Example -
Join set1 and set2, but keep only the duplicates:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = [Link](set2)
print(set3) # Output- {'apple'}
We can use the & operator instead of the intersection() method, and you will get the same
result.
set3 = set1 & set2
Note: The & operator only allows you to join sets with sets, and not with other data types
like you can with the intersecton() method.
The intersection_update() method will also keep ONLY the duplicates, but it will change the
original set instead of returning a new set. Example -
Keep the items that exist in both set1, and set2:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set1.intersection_update(set2)
print(x)
The values True and 1 are considered the same value. The same goes for False and 0.
Example-
Join sets that contains the values True, False, 1, and 0, and considered as duplicates:
set1 = {"apple", 1, "banana", 0, "cherry"}
set2 = {False, "google", 1, "apple", 2, True}
set3 = [Link](set2)
print(set3) Difference
The difference() method will return a new set that will contain only the items from the first
set that are not present in the other set. Example -
Keep all items from set1 that are not in set2:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = [Link](set2)
print(set3) # output- {'banana', 'cherry'}
We can use the - operator instead of the difference() method, and you will get the same
result.
set3 = set1 - set2
Note: The - operator only allows you to join sets with sets, and not with other data types
like you can with the difference() method.
The difference_update() method will also keep the items from the first set that are not in
the other set, but it will change the original set instead of returning a new set.
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set1.difference_update(set2)
print(set1)
Symmetric Differences
The symmetric_difference() method will keep only the elements that are NOT present in
both sets. Example-
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1.symmetric_difference(set2)
print(set3) # Output - {'google', 'banana', 'microsoft', 'cherry'}
We can use the ^ operator instead of the symmetric_difference() method, and we will get
the same result. Example - Use ^ to join two sets:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1 ^ set2
print(set3) # Output - {'google', 'banana', 'microsoft', 'cherry'}
Note: The ^ operator only allows you to join sets with sets, and not with other data types
like you can with the symmetric_difference() method.
The symmetric_difference_update() method will also keep all but the duplicates, but it will
change the original set instead of returning a new set.
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set1.symmetric_difference_update(set2)
print(set1) # Output - {'google', 'banana', 'microsoft', 'cherry'}
Dictionary
Dictionaries are used to store data values in key : value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
As of Python version 3.7, dictionaries are ordered.
In Python 3.6 and earlier, dictionaries are unordered.
Dictionaries are written with curly brackets, and can be referred to by using key name. Ex.
mydict = { "Name": "Dinesh", "Age": 24, "City": "Kota"}
print(mydict["Name"])
Duplicate values will overwrite existing values: Ex. –
mydict = { "Name": "Dinesh", "Age": 24, ,”Age”:26,"City": "Kota"}
print(mydict["Name"])
To determine how many items a dictionary has, use the len() function.
Ex. print(len(mtdict)) # output -3
The values in dictionary items can be of any data type: Ex.
mydict = {
"Name": "Dinesh",
"Age": 24,
"City": "Kota",
"mylist":[10,20,30,40]
}
print(mydict) The dict() Constructor
It is also possible to use the dict() constructor to make a dictionary. Example -
thisdict = dict(name = “Vijay", age = 36, country = “India")
print(thisdict)
Access Dictionary Items
We can access the items of a dictionary by referring to its key name, inside square brackets.
mydict = {
"Name": "Vijay",
"Class": "[Link] IV Sem",
"year": 2024
}
x = mydict["Class"]
print(x)
There is also a method called get() that will give you the same result.
Example- x = [Link]("model")
The keys() method will return a list of all the keys in the dictionary. Example-
mydict = {
"Name": "Vijay",
"Class": "[Link] IV Sem",
"year": 2024
}
x = [Link]()
print(x) # Output- dict_keys(['Name', 'Class', 'year'])
Add a new item to the original dictionary, and see that the keys list gets updated as well-
mydict["Age"]=21
x = [Link]()
print(x) # Output - dict_keys(['Name', 'Class', 'year', 'Age'])
Get Values
The values() method will return a list of all the values in the dictionary. Example –
mydict = {
"Name": "Vijay",
"Class": "[Link] IV Sem",
"year": 2024
}
x = [Link]()
print(x) # Output - dict_values(['Vijay', '[Link] IV Sem', 2024])
Get Items
The items() method will return each item in a dictionary, as tuples in a list. Example-
mydict = {
"Name": "Vijay",
"Class": "[Link] IV Sem",
"year": 2024
}
x = [Link]()
print(x) # Output- dict_items([('Name', 'Vijay'), ('Class', '[Link] IV Sem'), ('year', 2024)])
Check if Key Exists
To determine if a specified key is present in a dictionary use the in keyword.
Example-
if "year" in mydict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Change Values
We can change the value of a specific item by referring to its key name. Example –
mydict["year"] = 2021
Update Dictionary
The update() method will update the dictionary with the items from the given argument. If
the item does not exist, the item will be added. The argument must be a dictionary, with
key:value pairs. Example-
[Link]({"year": 2020})
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to
it. Example-
mydict*“rollno"] = 214266
Removing Items
There are several methods to remove items from a dictionary.
The pop() method removes the item with the specified key name. Example-
[Link](“year")
The popitem() method removes the last inserted item (in versions before 3.7, a random
item is removed instead). Example-
[Link]()
The del keyword removes the item with the specified key name. Example-
del mydict*“year"+
The del keyword can also delete the dictionary completely. Example – del mydict
The clear() method empties the dictionary. Example- [Link]()
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but
there are methods to return the values as well.
Example- Print all key names in the dictionary, one by one:
mydict = {
"Name": "Vijay",
"Class": "[Link] IV Sem",
"year": 2024
}
for x in mydict:
print(x)
Print all values in the dictionary, one by one. Example-
for x in mydict:
print(mydict[x])
We can also use the values() method to return values of a dictionary. Example-
for x in [Link]():
print(x)
We can use the keys() method to return the keys of a dictionary. Example –
for x in [Link]():
print(x)
Loop through both keys and values, by using the items() method. Example-
for x, y in [Link]():
print(x, y)
Copy a Dictionary
We cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be
a reference to dict1, and changes made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Example- dict2 = [Link]()
Another way to make a copy is to use the built-in function dict().
Example - dict2 = dict(dict1)
Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries. Example-
Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : { "name" : “Anil", "year" : 2004 },
"child2" : { "name" : “Sunil", "year" : 2007 },
"child3" : { "name" : “Rohit", "year" : 2011 } }
Or, if you want to add three dictionaries into a new dictionary: Example -
Create three dictionaries, then create one dictionary that will contain the other three
dictionaries:
child1 = { "name" : “Anil", "year" : 2004 }
child2 = { "name" : “Sunil", "year" : 2007 }
child3 = { "name" : “Romil", "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"])
Loop Through Nested Dictionaries
We can loop through a dictionary by using the items() method like this: Example-
myfamily = {
"child1" : {"name" : "Vijay","year" : 2004},
"child2" : {"name" : "Sanjay","year" : 2007},
"child3" : {"name" : "Rohit", "year" : 2011 } }
for x, ch in [Link]():
print(x)
for y in ch:
print(y + ':', ch[y])
print(" ") Output
child1
name: Vijay
year: 2004
child2
name: Sanjay
year: 2007
child3
name: Rohit
year: 2011
End of Part 3
Total slides 32