SlideShare a Scribd company logo
Python List Tuple & dictionary
Prof. K. Adisesha| 1
Python Lists
Python Collections (Arrays)
There are four collection data types in the Python programming language:
 List is a collection, which is ordered and changeable. Allows duplicate members.
 Tuple is a collection, which is ordered and unchangeable. Allows duplicate members.
 Set is a collection, which is unordered and unindexed. No duplicate members.
 Dictionary is a collection, which is unordered, changeable and indexed. No duplicate
members.
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.
List: A list is a collection, which is ordered and changeable. In Python, lists are written with
square brackets.
Example
Create a List:
StuList = ["Prajwal", "Sunny", "Rekha"]
print(StuList)
Output: ['Prajwal', 'Sunny', 'Rekha']
Access Items: You access the list items by referring to the index number:
Example
Print the second item of the list:
StuList = ["Prajwal", "Sunny", "Rekha"]
print(StuList[1])
Output: Sunny
Negative Indexing: Negative indexing means beginning 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:
StuList = ["Prajwal", "Sunny", "Rekha"]
print(StuList[-1])
Output: Rekha
Range of Indexes: You can specify a range of indexes by specifying start and end position of 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:
StuList = ["Prajwal", "Sunny", "Rekha", "Sam", "Adi", "Ram", "Shilu"]
print(StuList[2:5])
Python List Tuple & dictionary
Prof. K. Adisesha| 2
Output: ["Rekha", "Sam", "Adi"]
Note: The search will start at index 2 (included) and end at index 5 (not included).
Range of Negative Indexes: Specify negative indexes if you want to start the search from the end
of the list:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
StuList = ["Prajwal", "Sunny", "Rekha", "Sam", "Adi", "Ram", "Shilu"]
print(StuList[-4:-1])
Output: ["Sam", "Adi", "Ram"]
Change Item Value: To change the value of a specific item, refer to the index number:
Example
Change the second item:
StuList = ["Prajwal", "Sunny", "Rekha"]
StuList[1] = "Adi"
print(StuList)
Output: ["Prajwal", "Adi", "Rekha"]
Loop through a List: You can loop through the list items by using a for loop:
Example
Print all items in the list, one by one:
StuList = ["Prajwal", "Sunny", "Rekha"]
for x in StuList:
print(x)
Output: Prajwal
Sunny
Rekha
Check if Item Exists: To determine if a specified item is present in a list use the in keyword:
Example
Check if “Sunny” is present in the list:
StuList = ["Prajwal", "Sunny", "Rekha"]
if "Prajwal" in StuList:
print("Yes, 'Sunny' is in the Student list")
Output: Yes, 'Sunny' is in the Student list
List Length
len() method: To determine how many items a list has use the:
Example
Print the number of items in the list:
StuList = ["Prajwal", "Sunny", "Rekha"]
print(len(StuList))
Output: 3
Python List Tuple & dictionary
Prof. K. Adisesha| 3
Add Items: To add an item to the end of the list, use the append), insert(), method:
 Using the append() method to append an item:
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
StuList.append("Sam")
print(StuList)
Output: ['Prajwal', 'Sunny', 'Rekha', 'Sam']
 To add an item at the specified index, use the insert() method:
Example
Insert an item as the second position:
StuList = ["Prajwal", "Sunny", "Rekha"]
StuList.insert(1, "Sam")
print(StuList)
Output: ['Prajwal', 'Sam', 'Sunny', 'Rekha']
Remove Item: There are several methods to remove items from a list using: remove(), pop(), del,
clear()
 The remove() method removes the specified item:
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
StuList.remove("Sunny")
print(StuList)
Output: ['Prajwal', 'Rekha']
 The pop() method removes the specified index, (or the last item if index is not specified):
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
StuList.pop()
print(StuList)
Output: ['Prajwal', 'Sunny']
 The del keyword removes the specified index:
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
del StuList[0]
print(StuList)
Output: ['Sunny', 'Rekha']
 The del keyword can also delete the list completely:
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
del StuList
Python List Tuple & dictionary
Prof. K. Adisesha| 4
 The clear() method empties the list:
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
StuList.clear()
print(StuList)
Copy a List: You 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 copy(), list() method.
 copy() method: Make a copy of a list:
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
mylist = StuList.copy()
print(mylist)
Output: ['Prajwal', 'Sunny', 'Rekha']
 list() method: Make a copy of a list:
Example
StuList = ["Prajwal", "Sunny", "Rekha"]
mylist = list(StuList)
print(mylist)
Output: ['Prajwal', 'Sunny', 'Rekha']
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)
Output: ['a', 'b', 'c', 1, 2, 3]
Another way to join two lists are by appending all the items from list2 into list1, one by one:
Example
Append list2 into list1:
list1 = ["a", "b”, "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Output: ['a', 'b', 'c', 1, 2, 3]
 Use the extend() method, which purpose is to add elements from one list to another list:
Example
Python List Tuple & dictionary
Prof. K. Adisesha| 5
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b”, "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Output: ['a', 'b', 'c', 1, 2, 3]
The list() Constructor: It is also possible to use the list() constructor to make a new list.
Example
Using the list() constructor to make a List:
StuList = list(("Prajwal", "Sunny", "Rekha")) # note the double round-brackets
print(StuList)
Output: ['Prajwal', 'Sunny', 'Rekha']
List Methods
Python has a set of built-in methods that you can use on lists.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Python List Tuple & dictionary
Prof. K. Adisesha| 6
Python Tuples
A tuple is a collection, which is ordered and unchangeable. In Python, tuples are written with
round brackets.
Example
Create a Tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
print(Stu_tuple)
Output: ('Prajwal', 'Sunny', 'Rekha')
Access Tuple Items: Tuple items access by referring to the index number, inside square
brackets:
Example
Print the second item in the tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
print(Stu_tuple[1])
Output: Sunny
Negative Indexing: Negative indexing means beginning from the end, -1 refers to the last item,
and -2 refers to the second last item etc.
Example
Print the last item of the tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
print(Stu_tuple[-1])
Output: Rekha
Range of Indexes: You can specify a range of indexes by specifying start and end of the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Return the third, fourth, and fifth item:
Stu_tuple = ("Prajwal", "Sunny", "Rekha", "Sam", "Adi", "Ram", "Shilu")
print(Stu_tuple[2:5])
Output: (“Rekha", "Sam", "Adi”)
Note: The search will start at index 2 (included) and end at index 5 (not included).
Range of Negative Indexes: Specify negative indexes if you want to start the search from the end
of the tuple:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
Stu_tuple = ("Prajwal", "Sunny", "Rekha", "Sam", "Adi", "Ram", "Shilu")
print(Stu_tuple[-4:-1])
Output: ("Sam", "Adi", "Ram")
Python List Tuple & dictionary
Prof. K. Adisesha| 7
Change Tuple Values: Once a tuple is created, you cannot change its values. Tuples are
unchangeable or immutable as it also is called. However, by converting 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 = (“Prajwal”, “Sunny”, “Rekha”)
y = list(x)
y[1] = "Adi"
x = tuple(y)
print(x)
Output: (“Prajwal”, “Adi”, “Rekha”)
Loop through a Tuple: You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
for x in Stu_tuple:
print(x,”t”)
Output: Prajwal Sunny Rekha
Check if Item Exists: To determine if a specified item is present in a tuple use the in keyword:
Example
Check if "Prajwal" is present in the tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
if "Prajwal" in Stu_tuple:
print("Yes, 'Prajwal' is in the Student tuple")
Output: Yes, 'Prajwal' is in the Student tuple
Tuple Length: To determine how many items a tuple has, use the len() method:
Example
Print the number of items in the tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
print(len(Stu_tuple))
Output: 3
Adding Items: Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Example
You cannot add items to a tuple:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
Stu_tuple[3] = "Adi" # This will raise an error
print(Stu_tuple) Output: TypeError: 'tuple' object does not support item assignment
Create Tuple With One Item: To create a tuple with only one item, you have add a comma
after the item, unless Python will not recognize the variable as a tuple.
Python List Tuple & dictionary
Prof. K. Adisesha| 8
Example
One item tuple, remember the comma:
Stu_tuple = ("Prajwal",)
print(type(Stu_tuple))
Stu_tuple = ("Prajwal") #NOT a tuple
print(type(Stu_tuple))
Output: <class 'tuple'>
<class 'str'>
Remove Items: Tuples are unchangeable, so you cannot remove items from it, but you can delete
the tuple completely:
Example
The del keyword can delete the tuple completely:
Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”)
del Stu_tuple
print(Stu_tuple) #this will raise an error because the tuple no longer exists
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)
Output: ('a', 'b', 'c', 1, 2, 3)
The tuple() Constructor: It is also possible to use the tuple() constructor to make a tuple.
Example
Using the tuple() method to make a tuple:
Stu_tuple = tuple((“Prajwal”, “Sunny”, “Rekha”)) # note the double round-brackets
print(Stu_tuple)
Output: ('Prajwal', 'Sunny', 'Rekha')
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of where it
was found
Python List Tuple & dictionary
Prof. K. Adisesha| 9
Dictionaries
Introduction
 Dictionaries are mutable unordered collections of data values in the form of key: value pairs.
 Dictionaries are also called associative arrays or mappings or hashes
 The keys of the dictionary must be of immutable type like strings and numbers. Tuples can also
be used as keys if they contain only immutable objects. Giving a mutable key like a list will
give you a TypeError:unhashable type" error
 Values in the dictionaries can be of any type.
 The curly brackets mark the beginning and end of the dictionary.
 Each entry (Key: Value) consists of a pair separated by a colon (:) between them.
 The key-value pairs are separated by commas (,)
Dictionary-name = {<key1> :< value1>, <key2> :< value2>...}
e.g Day 0f The Week "Sunday":1, "Monday" 2, "Tuesday":3, "Wednesday":4,
"Thursday":5, "Friday":6,"Saturday":7)
 As the elements (key, value pairs) in a dictionary are unordered, we cannot access elements as
per any specific order. Dictionaries are not a sequence like string, list and tuple.
 The key value pairs are held in a dictionary as references.
 Keys in a dictionary have to be unique.
Definitions:
Dictionary is listed in curly brackets { }, inside these curly brackets, keys and values are declared.
Each key is separated from its value by a colon (:) while commas separate each element.
To create a dictionary, you need to include the key: value pairs in a curly braces as per following
syntax:
my_dict = {'key1': 'value1','key2': 'value2','key3': 'value3'…'keyn': 'valuen'}
Example:
dictr = {'Name': Sunny', 'Age': 18, 'Place': 'Bangalore'}
Properties of Dictionary Keys?
 There are two important points while using dictionary keys
 More than one entry per key is not allowed ( no duplicate key is allowed)
 The values in the dictionary can be of any type while the keys must be immutable like
numbers, tuples or strings.
 Dictionary keys are case sensitive- Same key name but with the different case are treated
as different keys in Python dictionaries.
Python List Tuple & dictionary
Prof. K. Adisesha| 10
Creation, initializing and accessing the elements in a Dictionary
The function dict ( ) is used to create a new dictionary with no items. This function is
called built-in function. We can also create dictionary using {}.
Example:
>>> D=dict()
>>> print D
{}
{} represents empty string. To add an item to the dictionary (empty string), we can use
square brackets for accessing and initializing dictionary values.
Example
>>> H=dict()
>>> H["one"]="keyboard"
>>> H["two"]="Mouse"
>>> H["three"]="printer"
>>> H["Four"]="scanner"
>>> print H
{'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
Traversing a dictionary
Let us visit each element of the dictionary to display its values on screen. This can be done by
using ‘for-loop’.
Example
H={'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'}
for i in H:
print i,":", H[i]," ",
Output
>>> Four: scanner one: keyboard three: printer two: Mouse
Creating, initializing values during run time (Dynamic allocation)
We can create a dictionary during run time also by using dict () function. This way of creation is
called dynamic allocation. Because, during the run time, memory keys and values are added to
the dictionary.
Example
Appending values to the dictionary
We can add new elements to the existing dictionary, extend it with single pair of values or join
two dictionaries into one. If we want to add only one element to the dictionary, then we should
use the following method.
Syntax:
Dictionary name [key]=value
Python List Tuple & dictionary
Prof. K. Adisesha| 11
List few Dictionary Methods?
Python has a set of built-in methods that you can use on dictionaries.
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and values
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not
exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
clear ( ) Method: It removes all items from the particular dictionary.
Syntax:
d.clear( ) #d dictionary
Example
Day={'mon':'Monday','tue':'Tuesday','wed':'Wednesday'}
print Day
Day.clear( )
print Day
Output: {'wed': 'Wednesday', 'mon': 'Monday', 'tue': 'Tuesday'}
{}
cmp ( ) Method: This is used to check whether the given dictionaries are same or not. If both are
same, it will return ‘zero’, otherwise return 1 or -1. If the first dictionary having more number of
items, then it will return 1, otherwise return -1.
Syntax:
cmp(d1,d2) #d1and d2 are dictionary.
Python List Tuple & dictionary
Prof. K. Adisesha| 12
returns 0 or 1 or -1
Example
Day1={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
Day2={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
Day3={'1':'Sun','2':'Mon','3':'Tues','4':'Wed'}
cmp(D1,D3) #both are not equal
Output: 1
cmp(D1,D2) #both are equal
Output: 0
cmp(D3,D1)
Output: -1
del() Method: This is used to Removing an item from dictionary. We can remove item from the
existing dictionary by using del key word.
Syntax:
del dicname[key]
Example
Day1={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
del Day1["3"]
print Day
Output: {'1':'Sun','2':'Mon',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
len( ) Method: This method returns number of key-value pairs in the given dictionary.
Syntax:
len(d) #d dictionary returns number of items in the list.
Example
Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
len(Day)
Output: 4
Merging dictionaries: An update ( )
Two dictionaries can be merged in to one by using update ( ) method. It merges the
keys and values of one dictionary into another and overwrites values of the same key.
Syntax:
Dic_name1.update (dic_name2)
Using this dic_name2 is added with Dic_name1.
Example
>>> d1={1:10,2:20,3:30}
>>> d2={4:40,5:50}
>>> d1.update(d2)
>>> print d1
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
get(k, x ) Method: There are two arguments (k, x) passed in ‘get( )’ method. The first argument
is key value, while the second argument is corresponding value. If a dictionary has a given key
(k), which is equal to given value (x), it returns the corresponding value (x) of given key (k). If
omitted and the dictionary has no key equal to the given key value, then it returns None.
Syntax:
D.get (k, x) #D dictionary, k key and x value
Python List Tuple & dictionary
Prof. K. Adisesha| 13
Example
Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
 Day.get('4',"wed") # corresponding value 3 'Wed'
 Day.get("6","mon") # default value of 6 ‘fri’
 Day.get("2") # default value of 2 ‘mon’
 Day.get("8") # None
has_key( ) Method: This function returns ‘True’, if dictionary has a key, otherwise it returns
‘False’.
Syntax:
D.has_key(k) #D dictionary and k key
Example
Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
D.has_key("2")
True
D.has_key("8")
False
items( ) Method: It returns the content of dictionary as a list of key and value. The key and
value pair will be in the form of a tuple, which is not in any particular order.
Syntax:
D.items() # D dictionary
Example
Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
D.items()
['1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat']
keys() Method: It returns a list of the key values in a dictionary, which is not in any particular
order.
Syntax:
D.keys( ) #D dictionary
Example
Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
D.keys()
[1', '2', 3', 4', '5', '6, 7']
values() Method: It returns a list of values from key-value pairs in a dictionary, which is not in
any particular order. However, if we call both the items () and values() method without changing
the dictionary's contents between these two (items() and values()), Python guarantees that the
order of the two results will be the same.
Syntax:
D.values() #D values
Example
Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
Python List Tuple & dictionary
Prof. K. Adisesha| 14
Day.values()
['Wed', 'Sun, 'Thu', 'Tue', 'Mon', 'Fri', 'Sat']
Day.items()
['1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat']
Python Dictionaries
What is Dictionary?
Dictionary is listed in curly brackets { }, inside these curly brackets, keys and values are declared.
Each key is separated from its value by a colon (:) while commas separate each element.
How to creating a Dictionary?
To create a dictionary, you need to include the key: value pairs in a curly braces as per following
syntax:
<dictionary-name>={<key>:<Value>, <key>:<Value>,...}
Example:
dictr = {'Name': Sunny', 'Age': 18, 'Place': 'Bangalore'}
What are the properties of Dictionary Keys?
 There are two important points while using dictionary keys
 More than one entry per key is not allowed ( no duplicate key is allowed)
 The values in the dictionary can be of any type while the keys must be immutable like
numbers, tuples or strings.
 Dictionary keys are case sensitive- Same key name but with the different case are treated
as different keys in Python dictionaries.
How to access elements from a dictionary?
While indexing is used with other container types to access values, dictionary uses keys. Key can
be used either inside square brackets or with the get() method.
Example:
>>>dict = {'Name':Sunny', 'Age': 18,'Place':'Bangalore'}
>>>print(my_dict['name'])
# Output: Sunny
There is also a method called get() that will give you the same result:
>>>print(dict.get('age'))
# Output: 18
Python List Tuple & dictionary
Prof. K. Adisesha| 15
How to change or add elements in a dictionary?
Dictionary are mutable. We can add new items or change the value of existing items using
assignment operator.
If the key is already present, value gets updated, else a new key: value pair is added to the
dictionary.
dict = {'Name':Sunny', 'Age': 18,'Place':'Bangalore'}
update value to Dictionary
dict['age'] = 27
print(dict)
#Output: {'age': 27, 'name': 'Sunny'}
add item to Dictionary
dict['address'] = 'Downtown'
print(dict)
Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
How to delete or remove elements from a dictionary?
We can remove a particular item in a dictionary by using the method pop(). This method removes
as item with the provided key and returns the value.
The method, popitem() can be used to remove and return an arbitrary item (key, value) form the
dictionary. All the items can be removed at once using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
# create a dictionary
dirc = {1:1, 2:4, 3:9, 4:16, 5:25}
# remove a particular item
>>>print(dirc.pop(4))
# Output: 16
>>>print(dirc)
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
# remove an arbitrary item
>>>print(dirc.popitem())
# Output: (1, 1)
# delete a particular item
>>>del dirc[5]
>>>print(squares)
Python List Tuple & dictionary
Prof. K. Adisesha| 16
Output: {2: 4, 3: 9}
# remove all items
dirc.clear()
>>>print(dirc)
# Output: {}
# delete the dictionary itself
>>>del squares
>>> print(dirc)
Output: Throws Error
Dictionary Membership Test
We can test if a key is in a dictionary or not using the keyword in. Notice that membership test is
for keys only, not for values.
Example:
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
Case1:
print(1 in squares)
# Output: True
Case2:
print(2 not in squares)
# Output: True
Loop Through a Dictionary
Loop through a dictionary is done through 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:
for x in thisdict:
print(x)
Example
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Example
You can also use the values() function to return values of a dictionary:
Python List Tuple & dictionary
Prof. K. Adisesha| 17
for x in thisdict.values():
print(x)
Example
Loop through both keys and values, by using the items() function:
for x, y in thisdict.items():
print(x, y)
Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use the len() method.
Example
Print the number of items in the dictionary:
print(len(thisdict))
Copy a Dictionary
You 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
Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Another way to make a copy is to use the built-in method dict().
Example
Make a copy of a dictionary with the dict() method:
Ruthisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)Run example »
n example »
Write a python program to input ‘n’ names and phone numbers to store it in a dictionary and to
input any name and to print the phone number of that particular name.
Code
Python List Tuple & dictionary
Prof. K. Adisesha| 18
phonebook=dict()
n=input("Enter total number of friends: ")
i=1
while i<=n:
a=raw_input("enter name: ")
b=raw_input("enter phone number: ")
phonebook[a]=b
i=i+1
name=input("enter name :")
f=0
l=phonebook.keys()
for i in l:
if (cmp(i,name)==0):
print "Phone number= ",phonebook[i]
f=1
if (f==0):
print "Given name not exist"
Output
Enter total number of friends 2
enter name: Prajwal
enter phone number: 23456745
enter name: Sunny
enter phone number: 45678956
2. Write a program to input ‘n’ employee number and name and to display all employee’s
information in ascending order based upon their number.
Code
empinfo=dict()
n=input("Enter total number of employees")
i=1
while i<=n:
a=raw_input("enter number")
b=raw_input("enter name")
empinfo[a]=b
i=i+1
l=empinfo.keys()
l.sort()
print "Employee Information"
print "Employee Number",'t',"Employee Name"
for i in l:
print i,'t',empinfo[i]
3. Write the output for the following Python codes.
A={1:100,2:200,3:300,4:400,5:500}
print A.items()
print A.keys()
print A.values()
Python List Tuple & dictionary
Prof. K. Adisesha| 19
Output
[(1, 100), (2, 200), (3, 300), (4, 400), (5, 500)]
[1, 2, 3, 4, 5]
[100, 200, 300, 400, 500]
4. Write a program to create a phone book and delete particular phone number using name.
Code
phonebook=dict()
n=input("Enter total number of friends")
i=1
while i<=n:
a=raw_input("enter name")
b=raw_input("enter phone number")
phonebook[a]=b
i=i+1
name=raw_input("enter name")
del phonebook[name]
l=phonebook.keys()
print "Phonebook Information"
print "Name",'t',"Phone number"
for i in l:
print i,'t',phonebook[i]
Write a program to input total number of sections and class teachers’ name in 11th class
and display all information on the output screen.
Code
classxi=dict()
n=input("Enter total number of section in xi class")
i=1
while i<=n:
a=raw_input("enter section")
b=raw_input ("enter class teacher name")
classxi[a]=b
i=i+1
print "Class","t","Section","t","teacher name"
for i in classxi:
print "XI","t",i,"t",classxi[i]

More Related Content

What's hot

Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
nitamhaske
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arraysphanleson
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in Scala
Knoldus Inc.
 
Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Sequence and Traverse - Part 3
Sequence and Traverse - Part 3
Philip Schwarz
 
[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell
Functional Thursday
 
Type Parameterization
Type ParameterizationType Parameterization
Type Parameterization
Knoldus Inc.
 
Python Collections
Python CollectionsPython Collections
Python Collections
sachingarg0
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Philip Schwarz
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
goncharenko
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
List in Python
List in PythonList in Python
List in Python
Siddique Ibrahim
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
Skills Matter
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
Praveen M Jigajinni
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
Emertxe Information Technologies Pvt Ltd
 

What's hot (18)

Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Effective way to code in Scala
Effective way to code in ScalaEffective way to code in Scala
Effective way to code in Scala
 
Sequence and Traverse - Part 3
Sequence and Traverse - Part 3Sequence and Traverse - Part 3
Sequence and Traverse - Part 3
 
[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell[FLOLAC'14][scm] Functional Programming Using Haskell
[FLOLAC'14][scm] Functional Programming Using Haskell
 
Pytho_tuples
Pytho_tuplesPytho_tuples
Pytho_tuples
 
Type Parameterization
Type ParameterizationType Parameterization
Type Parameterization
 
Python Collections
Python CollectionsPython Collections
Python Collections
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
 
Functional Programming by Examples using Haskell
Functional Programming by Examples using HaskellFunctional Programming by Examples using Haskell
Functional Programming by Examples using Haskell
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
List in Python
List in PythonList in Python
List in Python
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
 
Python : Regular expressions
Python : Regular expressionsPython : Regular expressions
Python : Regular expressions
 

Similar to Python data handling notes

Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
narmadhakin
 
The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212
Mahmoud Samir Fayed
 
The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210
Mahmoud Samir Fayed
 
The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184
Mahmoud Samir Fayed
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
ssuser8e50d8
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
NehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
NehaSpillai1
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
Koteswari Kasireddy
 
The Ring programming language version 1.5.4 book - Part 22 of 185
The Ring programming language version 1.5.4 book - Part 22 of 185The Ring programming language version 1.5.4 book - Part 22 of 185
The Ring programming language version 1.5.4 book - Part 22 of 185
Mahmoud Samir Fayed
 
List in Python
List in PythonList in Python
List in Python
Sharath Ankrajegowda
 
Lists
ListsLists
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
AshaWankar1
 
Python Lists.pptx
Python Lists.pptxPython Lists.pptx
Python Lists.pptx
adityakumawat625
 
Python PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptxPython PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptx
NeyXmarXd
 
The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189
Mahmoud Samir Fayed
 
Sixth session
Sixth sessionSixth session
Sixth session
AliMohammad155
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
Asst.prof M.Gokilavani
 
Python data structures
Python data structuresPython data structures
Python data structures
kalyanibedekar
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
Prof. Dr. K. Adisesha
 

Similar to Python data handling notes (20)

Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212The Ring programming language version 1.10 book - Part 30 of 212
The Ring programming language version 1.10 book - Part 30 of 212
 
The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210The Ring programming language version 1.9 book - Part 29 of 210
The Ring programming language version 1.9 book - Part 29 of 210
 
The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202The Ring programming language version 1.8 book - Part 27 of 202
The Ring programming language version 1.8 book - Part 27 of 202
 
The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
 
The Ring programming language version 1.5.4 book - Part 22 of 185
The Ring programming language version 1.5.4 book - Part 22 of 185The Ring programming language version 1.5.4 book - Part 22 of 185
The Ring programming language version 1.5.4 book - Part 22 of 185
 
List in Python
List in PythonList in Python
List in Python
 
Lists
ListsLists
Lists
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
Python Lists.pptx
Python Lists.pptxPython Lists.pptx
Python Lists.pptx
 
Python PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptxPython PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptx
 
The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189
 
Sixth session
Sixth sessionSixth session
Sixth session
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
Python data structures
Python data structuresPython data structures
Python data structures
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 

More from Prof. Dr. K. Adisesha

Software Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdfSoftware Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdfSoftware Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdfSoftware Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdfSoftware Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdfSoftware Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Prof. Dr. K. Adisesha
 
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdfSoftware Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Prof. Dr. K. Adisesha
 
Computer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. AdiseshaComputer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. Adisesha
Prof. Dr. K. Adisesha
 
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. AdiaeshaCCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
Prof. Dr. K. Adisesha
 
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. AdiseshaCCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
Prof. Dr. K. Adisesha
 
CCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. AdiseshaCCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. Adisesha
Prof. Dr. K. Adisesha
 
CCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdfCCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdf
Prof. Dr. K. Adisesha
 
Introduction to Computers.pdf
Introduction to Computers.pdfIntroduction to Computers.pdf
Introduction to Computers.pdf
Prof. Dr. K. Adisesha
 
R_Programming.pdf
R_Programming.pdfR_Programming.pdf
R_Programming.pdf
Prof. Dr. K. Adisesha
 
Scholarship.pdf
Scholarship.pdfScholarship.pdf
Scholarship.pdf
Prof. Dr. K. Adisesha
 
Operating System-2 by Adi.pdf
Operating System-2 by Adi.pdfOperating System-2 by Adi.pdf
Operating System-2 by Adi.pdf
Prof. Dr. K. Adisesha
 
Operating System-1 by Adi.pdf
Operating System-1 by Adi.pdfOperating System-1 by Adi.pdf
Operating System-1 by Adi.pdf
Prof. Dr. K. Adisesha
 
Operating System-adi.pdf
Operating System-adi.pdfOperating System-adi.pdf
Operating System-adi.pdf
Prof. Dr. K. Adisesha
 
Data_structure using C-Adi.pdf
Data_structure using C-Adi.pdfData_structure using C-Adi.pdf
Data_structure using C-Adi.pdf
Prof. Dr. K. Adisesha
 
JAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdfJAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdf
Prof. Dr. K. Adisesha
 
JAVA PPT -5 BY ADI.pdf
JAVA PPT -5 BY ADI.pdfJAVA PPT -5 BY ADI.pdf
JAVA PPT -5 BY ADI.pdf
Prof. Dr. K. Adisesha
 

More from Prof. Dr. K. Adisesha (20)

Software Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdfSoftware Engineering notes by K. Adisesha.pdf
Software Engineering notes by K. Adisesha.pdf
 
Software Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdfSoftware Engineering-Unit 1 by Adisesha.pdf
Software Engineering-Unit 1 by Adisesha.pdf
 
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdfSoftware Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
Software Engineering-Unit 2 "Requirement Engineering" by Adi.pdf
 
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdfSoftware Engineering-Unit 3 "System Modelling" by Adi.pdf
Software Engineering-Unit 3 "System Modelling" by Adi.pdf
 
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdfSoftware Engineering-Unit 4 "Architectural Design" by Adi.pdf
Software Engineering-Unit 4 "Architectural Design" by Adi.pdf
 
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdfSoftware Engineering-Unit 5 "Software Testing"by Adi.pdf
Software Engineering-Unit 5 "Software Testing"by Adi.pdf
 
Computer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. AdiseshaComputer Networks Notes by -Dr. K. Adisesha
Computer Networks Notes by -Dr. K. Adisesha
 
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. AdiaeshaCCN Unit-1&2 Data Communication &Networking by K. Adiaesha
CCN Unit-1&2 Data Communication &Networking by K. Adiaesha
 
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. AdiseshaCCN Unit-3 Data Link Layer by Dr. K. Adisesha
CCN Unit-3 Data Link Layer by Dr. K. Adisesha
 
CCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. AdiseshaCCN Unit-4 Network Layer by Dr. K. Adisesha
CCN Unit-4 Network Layer by Dr. K. Adisesha
 
CCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdfCCN Unit-5 Transport & Application Layer by Adi.pdf
CCN Unit-5 Transport & Application Layer by Adi.pdf
 
Introduction to Computers.pdf
Introduction to Computers.pdfIntroduction to Computers.pdf
Introduction to Computers.pdf
 
R_Programming.pdf
R_Programming.pdfR_Programming.pdf
R_Programming.pdf
 
Scholarship.pdf
Scholarship.pdfScholarship.pdf
Scholarship.pdf
 
Operating System-2 by Adi.pdf
Operating System-2 by Adi.pdfOperating System-2 by Adi.pdf
Operating System-2 by Adi.pdf
 
Operating System-1 by Adi.pdf
Operating System-1 by Adi.pdfOperating System-1 by Adi.pdf
Operating System-1 by Adi.pdf
 
Operating System-adi.pdf
Operating System-adi.pdfOperating System-adi.pdf
Operating System-adi.pdf
 
Data_structure using C-Adi.pdf
Data_structure using C-Adi.pdfData_structure using C-Adi.pdf
Data_structure using C-Adi.pdf
 
JAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdfJAVA PPT -2 BY ADI.pdf
JAVA PPT -2 BY ADI.pdf
 
JAVA PPT -5 BY ADI.pdf
JAVA PPT -5 BY ADI.pdfJAVA PPT -5 BY ADI.pdf
JAVA PPT -5 BY ADI.pdf
 

Recently uploaded

Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 

Recently uploaded (20)

Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 

Python data handling notes

  • 1. Python List Tuple & dictionary Prof. K. Adisesha| 1 Python Lists Python Collections (Arrays) There are four collection data types in the Python programming language:  List is a collection, which is ordered and changeable. Allows duplicate members.  Tuple is a collection, which is ordered and unchangeable. Allows duplicate members.  Set is a collection, which is unordered and unindexed. No duplicate members.  Dictionary is a collection, which is unordered, changeable and indexed. No duplicate members. 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. List: A list is a collection, which is ordered and changeable. In Python, lists are written with square brackets. Example Create a List: StuList = ["Prajwal", "Sunny", "Rekha"] print(StuList) Output: ['Prajwal', 'Sunny', 'Rekha'] Access Items: You access the list items by referring to the index number: Example Print the second item of the list: StuList = ["Prajwal", "Sunny", "Rekha"] print(StuList[1]) Output: Sunny Negative Indexing: Negative indexing means beginning 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: StuList = ["Prajwal", "Sunny", "Rekha"] print(StuList[-1]) Output: Rekha Range of Indexes: You can specify a range of indexes by specifying start and end position of 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: StuList = ["Prajwal", "Sunny", "Rekha", "Sam", "Adi", "Ram", "Shilu"] print(StuList[2:5])
  • 2. Python List Tuple & dictionary Prof. K. Adisesha| 2 Output: ["Rekha", "Sam", "Adi"] Note: The search will start at index 2 (included) and end at index 5 (not included). Range of Negative Indexes: Specify negative indexes if you want to start the search from the end of the list: Example This example returns the items from index -4 (included) to index -1 (excluded) StuList = ["Prajwal", "Sunny", "Rekha", "Sam", "Adi", "Ram", "Shilu"] print(StuList[-4:-1]) Output: ["Sam", "Adi", "Ram"] Change Item Value: To change the value of a specific item, refer to the index number: Example Change the second item: StuList = ["Prajwal", "Sunny", "Rekha"] StuList[1] = "Adi" print(StuList) Output: ["Prajwal", "Adi", "Rekha"] Loop through a List: You can loop through the list items by using a for loop: Example Print all items in the list, one by one: StuList = ["Prajwal", "Sunny", "Rekha"] for x in StuList: print(x) Output: Prajwal Sunny Rekha Check if Item Exists: To determine if a specified item is present in a list use the in keyword: Example Check if “Sunny” is present in the list: StuList = ["Prajwal", "Sunny", "Rekha"] if "Prajwal" in StuList: print("Yes, 'Sunny' is in the Student list") Output: Yes, 'Sunny' is in the Student list List Length len() method: To determine how many items a list has use the: Example Print the number of items in the list: StuList = ["Prajwal", "Sunny", "Rekha"] print(len(StuList)) Output: 3
  • 3. Python List Tuple & dictionary Prof. K. Adisesha| 3 Add Items: To add an item to the end of the list, use the append), insert(), method:  Using the append() method to append an item: Example StuList = ["Prajwal", "Sunny", "Rekha"] StuList.append("Sam") print(StuList) Output: ['Prajwal', 'Sunny', 'Rekha', 'Sam']  To add an item at the specified index, use the insert() method: Example Insert an item as the second position: StuList = ["Prajwal", "Sunny", "Rekha"] StuList.insert(1, "Sam") print(StuList) Output: ['Prajwal', 'Sam', 'Sunny', 'Rekha'] Remove Item: There are several methods to remove items from a list using: remove(), pop(), del, clear()  The remove() method removes the specified item: Example StuList = ["Prajwal", "Sunny", "Rekha"] StuList.remove("Sunny") print(StuList) Output: ['Prajwal', 'Rekha']  The pop() method removes the specified index, (or the last item if index is not specified): Example StuList = ["Prajwal", "Sunny", "Rekha"] StuList.pop() print(StuList) Output: ['Prajwal', 'Sunny']  The del keyword removes the specified index: Example StuList = ["Prajwal", "Sunny", "Rekha"] del StuList[0] print(StuList) Output: ['Sunny', 'Rekha']  The del keyword can also delete the list completely: Example StuList = ["Prajwal", "Sunny", "Rekha"] del StuList
  • 4. Python List Tuple & dictionary Prof. K. Adisesha| 4  The clear() method empties the list: Example StuList = ["Prajwal", "Sunny", "Rekha"] StuList.clear() print(StuList) Copy a List: You 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 copy(), list() method.  copy() method: Make a copy of a list: Example StuList = ["Prajwal", "Sunny", "Rekha"] mylist = StuList.copy() print(mylist) Output: ['Prajwal', 'Sunny', 'Rekha']  list() method: Make a copy of a list: Example StuList = ["Prajwal", "Sunny", "Rekha"] mylist = list(StuList) print(mylist) Output: ['Prajwal', 'Sunny', 'Rekha'] 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) Output: ['a', 'b', 'c', 1, 2, 3] Another way to join two lists are by appending all the items from list2 into list1, one by one: Example Append list2 into list1: list1 = ["a", "b”, "c"] list2 = [1, 2, 3] for x in list2: list1.append(x) print(list1) Output: ['a', 'b', 'c', 1, 2, 3]  Use the extend() method, which purpose is to add elements from one list to another list: Example
  • 5. Python List Tuple & dictionary Prof. K. Adisesha| 5 Use the extend() method to add list2 at the end of list1: list1 = ["a", "b”, "c"] list2 = [1, 2, 3] list1.extend(list2) print(list1) Output: ['a', 'b', 'c', 1, 2, 3] The list() Constructor: It is also possible to use the list() constructor to make a new list. Example Using the list() constructor to make a List: StuList = list(("Prajwal", "Sunny", "Rekha")) # note the double round-brackets print(StuList) Output: ['Prajwal', 'Sunny', 'Rekha'] List Methods Python has a set of built-in methods that you can use on lists. Method Description append() Adds an element at the end of the list clear() Removes all the elements from the list copy() Returns a copy of the list count() Returns the number of elements with the specified value extend() Add the elements of a list (or any iterable), to the end of the current list index() Returns the index of the first element with the specified value insert() Adds an element at the specified position pop() Removes the element at the specified position remove() Removes the item with the specified value reverse() Reverses the order of the list sort() Sorts the list
  • 6. Python List Tuple & dictionary Prof. K. Adisesha| 6 Python Tuples A tuple is a collection, which is ordered and unchangeable. In Python, tuples are written with round brackets. Example Create a Tuple: Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”) print(Stu_tuple) Output: ('Prajwal', 'Sunny', 'Rekha') Access Tuple Items: Tuple items access by referring to the index number, inside square brackets: Example Print the second item in the tuple: Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”) print(Stu_tuple[1]) Output: Sunny Negative Indexing: Negative indexing means beginning from the end, -1 refers to the last item, and -2 refers to the second last item etc. Example Print the last item of the tuple: Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”) print(Stu_tuple[-1]) Output: Rekha Range of Indexes: You can specify a range of indexes by specifying start and end of the range. When specifying a range, the return value will be a new tuple with the specified items. Example Return the third, fourth, and fifth item: Stu_tuple = ("Prajwal", "Sunny", "Rekha", "Sam", "Adi", "Ram", "Shilu") print(Stu_tuple[2:5]) Output: (“Rekha", "Sam", "Adi”) Note: The search will start at index 2 (included) and end at index 5 (not included). Range of Negative Indexes: Specify negative indexes if you want to start the search from the end of the tuple: Example This example returns the items from index -4 (included) to index -1 (excluded) Stu_tuple = ("Prajwal", "Sunny", "Rekha", "Sam", "Adi", "Ram", "Shilu") print(Stu_tuple[-4:-1]) Output: ("Sam", "Adi", "Ram")
  • 7. Python List Tuple & dictionary Prof. K. Adisesha| 7 Change Tuple Values: Once a tuple is created, you cannot change its values. Tuples are unchangeable or immutable as it also is called. However, by converting 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 = (“Prajwal”, “Sunny”, “Rekha”) y = list(x) y[1] = "Adi" x = tuple(y) print(x) Output: (“Prajwal”, “Adi”, “Rekha”) Loop through a Tuple: You can loop through the tuple items by using a for loop. Example Iterate through the items and print the values: Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”) for x in Stu_tuple: print(x,”t”) Output: Prajwal Sunny Rekha Check if Item Exists: To determine if a specified item is present in a tuple use the in keyword: Example Check if "Prajwal" is present in the tuple: Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”) if "Prajwal" in Stu_tuple: print("Yes, 'Prajwal' is in the Student tuple") Output: Yes, 'Prajwal' is in the Student tuple Tuple Length: To determine how many items a tuple has, use the len() method: Example Print the number of items in the tuple: Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”) print(len(Stu_tuple)) Output: 3 Adding Items: Once a tuple is created, you cannot add items to it. Tuples are unchangeable. Example You cannot add items to a tuple: Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”) Stu_tuple[3] = "Adi" # This will raise an error print(Stu_tuple) Output: TypeError: 'tuple' object does not support item assignment Create Tuple With One Item: To create a tuple with only one item, you have add a comma after the item, unless Python will not recognize the variable as a tuple.
  • 8. Python List Tuple & dictionary Prof. K. Adisesha| 8 Example One item tuple, remember the comma: Stu_tuple = ("Prajwal",) print(type(Stu_tuple)) Stu_tuple = ("Prajwal") #NOT a tuple print(type(Stu_tuple)) Output: <class 'tuple'> <class 'str'> Remove Items: Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely: Example The del keyword can delete the tuple completely: Stu_tuple = (“Prajwal”, “Sunny”, “Rekha”) del Stu_tuple print(Stu_tuple) #this will raise an error because the tuple no longer exists 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) Output: ('a', 'b', 'c', 1, 2, 3) The tuple() Constructor: It is also possible to use the tuple() constructor to make a tuple. Example Using the tuple() method to make a tuple: Stu_tuple = tuple((“Prajwal”, “Sunny”, “Rekha”)) # note the double round-brackets print(Stu_tuple) Output: ('Prajwal', 'Sunny', 'Rekha') Tuple Methods Python has two built-in methods that you can use on tuples. Method Description count() Returns the number of times a specified value occurs in a tuple index() Searches the tuple for a specified value and returns the position of where it was found
  • 9. Python List Tuple & dictionary Prof. K. Adisesha| 9 Dictionaries Introduction  Dictionaries are mutable unordered collections of data values in the form of key: value pairs.  Dictionaries are also called associative arrays or mappings or hashes  The keys of the dictionary must be of immutable type like strings and numbers. Tuples can also be used as keys if they contain only immutable objects. Giving a mutable key like a list will give you a TypeError:unhashable type" error  Values in the dictionaries can be of any type.  The curly brackets mark the beginning and end of the dictionary.  Each entry (Key: Value) consists of a pair separated by a colon (:) between them.  The key-value pairs are separated by commas (,) Dictionary-name = {<key1> :< value1>, <key2> :< value2>...} e.g Day 0f The Week "Sunday":1, "Monday" 2, "Tuesday":3, "Wednesday":4, "Thursday":5, "Friday":6,"Saturday":7)  As the elements (key, value pairs) in a dictionary are unordered, we cannot access elements as per any specific order. Dictionaries are not a sequence like string, list and tuple.  The key value pairs are held in a dictionary as references.  Keys in a dictionary have to be unique. Definitions: Dictionary is listed in curly brackets { }, inside these curly brackets, keys and values are declared. Each key is separated from its value by a colon (:) while commas separate each element. To create a dictionary, you need to include the key: value pairs in a curly braces as per following syntax: my_dict = {'key1': 'value1','key2': 'value2','key3': 'value3'…'keyn': 'valuen'} Example: dictr = {'Name': Sunny', 'Age': 18, 'Place': 'Bangalore'} Properties of Dictionary Keys?  There are two important points while using dictionary keys  More than one entry per key is not allowed ( no duplicate key is allowed)  The values in the dictionary can be of any type while the keys must be immutable like numbers, tuples or strings.  Dictionary keys are case sensitive- Same key name but with the different case are treated as different keys in Python dictionaries.
  • 10. Python List Tuple & dictionary Prof. K. Adisesha| 10 Creation, initializing and accessing the elements in a Dictionary The function dict ( ) is used to create a new dictionary with no items. This function is called built-in function. We can also create dictionary using {}. Example: >>> D=dict() >>> print D {} {} represents empty string. To add an item to the dictionary (empty string), we can use square brackets for accessing and initializing dictionary values. Example >>> H=dict() >>> H["one"]="keyboard" >>> H["two"]="Mouse" >>> H["three"]="printer" >>> H["Four"]="scanner" >>> print H {'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'} Traversing a dictionary Let us visit each element of the dictionary to display its values on screen. This can be done by using ‘for-loop’. Example H={'Four': 'scanner', 'three': 'printer', 'two': 'Mouse', 'one': 'keyboard'} for i in H: print i,":", H[i]," ", Output >>> Four: scanner one: keyboard three: printer two: Mouse Creating, initializing values during run time (Dynamic allocation) We can create a dictionary during run time also by using dict () function. This way of creation is called dynamic allocation. Because, during the run time, memory keys and values are added to the dictionary. Example Appending values to the dictionary We can add new elements to the existing dictionary, extend it with single pair of values or join two dictionaries into one. If we want to add only one element to the dictionary, then we should use the following method. Syntax: Dictionary name [key]=value
  • 11. Python List Tuple & dictionary Prof. K. Adisesha| 11 List few Dictionary Methods? Python has a set of built-in methods that you can use on dictionaries. Method Description clear() Removes all the elements from the dictionary copy() Returns a copy of the dictionary fromkeys() Returns a dictionary with the specified keys and values get() Returns the value of the specified key items() Returns a list containing a tuple for each key value pair keys() Returns a list containing the dictionary's keys pop() Removes the element with the specified key popitem() Removes the last inserted key-value pair setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value update() Updates the dictionary with the specified key-value pairs values() Returns a list of all the values in the dictionary clear ( ) Method: It removes all items from the particular dictionary. Syntax: d.clear( ) #d dictionary Example Day={'mon':'Monday','tue':'Tuesday','wed':'Wednesday'} print Day Day.clear( ) print Day Output: {'wed': 'Wednesday', 'mon': 'Monday', 'tue': 'Tuesday'} {} cmp ( ) Method: This is used to check whether the given dictionaries are same or not. If both are same, it will return ‘zero’, otherwise return 1 or -1. If the first dictionary having more number of items, then it will return 1, otherwise return -1. Syntax: cmp(d1,d2) #d1and d2 are dictionary.
  • 12. Python List Tuple & dictionary Prof. K. Adisesha| 12 returns 0 or 1 or -1 Example Day1={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'} Day2={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'} Day3={'1':'Sun','2':'Mon','3':'Tues','4':'Wed'} cmp(D1,D3) #both are not equal Output: 1 cmp(D1,D2) #both are equal Output: 0 cmp(D3,D1) Output: -1 del() Method: This is used to Removing an item from dictionary. We can remove item from the existing dictionary by using del key word. Syntax: del dicname[key] Example Day1={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'} del Day1["3"] print Day Output: {'1':'Sun','2':'Mon',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'} len( ) Method: This method returns number of key-value pairs in the given dictionary. Syntax: len(d) #d dictionary returns number of items in the list. Example Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'} len(Day) Output: 4 Merging dictionaries: An update ( ) Two dictionaries can be merged in to one by using update ( ) method. It merges the keys and values of one dictionary into another and overwrites values of the same key. Syntax: Dic_name1.update (dic_name2) Using this dic_name2 is added with Dic_name1. Example >>> d1={1:10,2:20,3:30} >>> d2={4:40,5:50} >>> d1.update(d2) >>> print d1 {1: 10, 2: 20, 3: 30, 4: 40, 5: 50} get(k, x ) Method: There are two arguments (k, x) passed in ‘get( )’ method. The first argument is key value, while the second argument is corresponding value. If a dictionary has a given key (k), which is equal to given value (x), it returns the corresponding value (x) of given key (k). If omitted and the dictionary has no key equal to the given key value, then it returns None. Syntax: D.get (k, x) #D dictionary, k key and x value
  • 13. Python List Tuple & dictionary Prof. K. Adisesha| 13 Example Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}  Day.get('4',"wed") # corresponding value 3 'Wed'  Day.get("6","mon") # default value of 6 ‘fri’  Day.get("2") # default value of 2 ‘mon’  Day.get("8") # None has_key( ) Method: This function returns ‘True’, if dictionary has a key, otherwise it returns ‘False’. Syntax: D.has_key(k) #D dictionary and k key Example Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'} D.has_key("2") True D.has_key("8") False items( ) Method: It returns the content of dictionary as a list of key and value. The key and value pair will be in the form of a tuple, which is not in any particular order. Syntax: D.items() # D dictionary Example Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'} D.items() ['1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'] keys() Method: It returns a list of the key values in a dictionary, which is not in any particular order. Syntax: D.keys( ) #D dictionary Example Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'} D.keys() [1', '2', 3', 4', '5', '6, 7'] values() Method: It returns a list of values from key-value pairs in a dictionary, which is not in any particular order. However, if we call both the items () and values() method without changing the dictionary's contents between these two (items() and values()), Python guarantees that the order of the two results will be the same. Syntax: D.values() #D values Example Day={'1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'}
  • 14. Python List Tuple & dictionary Prof. K. Adisesha| 14 Day.values() ['Wed', 'Sun, 'Thu', 'Tue', 'Mon', 'Fri', 'Sat'] Day.items() ['1':'Sun','2':'Mon','3':'Tues',’4':'Wed','5':'Thu','6':'Fri,'7':'Sat'] Python Dictionaries What is Dictionary? Dictionary is listed in curly brackets { }, inside these curly brackets, keys and values are declared. Each key is separated from its value by a colon (:) while commas separate each element. How to creating a Dictionary? To create a dictionary, you need to include the key: value pairs in a curly braces as per following syntax: <dictionary-name>={<key>:<Value>, <key>:<Value>,...} Example: dictr = {'Name': Sunny', 'Age': 18, 'Place': 'Bangalore'} What are the properties of Dictionary Keys?  There are two important points while using dictionary keys  More than one entry per key is not allowed ( no duplicate key is allowed)  The values in the dictionary can be of any type while the keys must be immutable like numbers, tuples or strings.  Dictionary keys are case sensitive- Same key name but with the different case are treated as different keys in Python dictionaries. How to access elements from a dictionary? While indexing is used with other container types to access values, dictionary uses keys. Key can be used either inside square brackets or with the get() method. Example: >>>dict = {'Name':Sunny', 'Age': 18,'Place':'Bangalore'} >>>print(my_dict['name']) # Output: Sunny There is also a method called get() that will give you the same result: >>>print(dict.get('age')) # Output: 18
  • 15. Python List Tuple & dictionary Prof. K. Adisesha| 15 How to change or add elements in a dictionary? Dictionary are mutable. We can add new items or change the value of existing items using assignment operator. If the key is already present, value gets updated, else a new key: value pair is added to the dictionary. dict = {'Name':Sunny', 'Age': 18,'Place':'Bangalore'} update value to Dictionary dict['age'] = 27 print(dict) #Output: {'age': 27, 'name': 'Sunny'} add item to Dictionary dict['address'] = 'Downtown' print(dict) Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'} How to delete or remove elements from a dictionary? We can remove a particular item in a dictionary by using the method pop(). This method removes as item with the provided key and returns the value. The method, popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary. All the items can be removed at once using the clear() method. We can also use the del keyword to remove individual items or the entire dictionary itself. # create a dictionary dirc = {1:1, 2:4, 3:9, 4:16, 5:25} # remove a particular item >>>print(dirc.pop(4)) # Output: 16 >>>print(dirc) # Output: {1: 1, 2: 4, 3: 9, 5: 25} # remove an arbitrary item >>>print(dirc.popitem()) # Output: (1, 1) # delete a particular item >>>del dirc[5] >>>print(squares)
  • 16. Python List Tuple & dictionary Prof. K. Adisesha| 16 Output: {2: 4, 3: 9} # remove all items dirc.clear() >>>print(dirc) # Output: {} # delete the dictionary itself >>>del squares >>> print(dirc) Output: Throws Error Dictionary Membership Test We can test if a key is in a dictionary or not using the keyword in. Notice that membership test is for keys only, not for values. Example: squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} Case1: print(1 in squares) # Output: True Case2: print(2 not in squares) # Output: True Loop Through a Dictionary Loop through a dictionary is done through 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: for x in thisdict: print(x) Example Print all values in the dictionary, one by one: for x in thisdict: print(thisdict[x]) Example You can also use the values() function to return values of a dictionary:
  • 17. Python List Tuple & dictionary Prof. K. Adisesha| 17 for x in thisdict.values(): print(x) Example Loop through both keys and values, by using the items() function: for x, y in thisdict.items(): print(x, y) Dictionary Length To determine how many items (key-value pairs) a dictionary has, use the len() method. Example Print the number of items in the dictionary: print(len(thisdict)) Copy a Dictionary You 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 Make a copy of a dictionary with the copy() method: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } mydict = thisdict.copy() print(mydict) Another way to make a copy is to use the built-in method dict(). Example Make a copy of a dictionary with the dict() method: Ruthisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } mydict = dict(thisdict) print(mydict)Run example » n example » Write a python program to input ‘n’ names and phone numbers to store it in a dictionary and to input any name and to print the phone number of that particular name. Code
  • 18. Python List Tuple & dictionary Prof. K. Adisesha| 18 phonebook=dict() n=input("Enter total number of friends: ") i=1 while i<=n: a=raw_input("enter name: ") b=raw_input("enter phone number: ") phonebook[a]=b i=i+1 name=input("enter name :") f=0 l=phonebook.keys() for i in l: if (cmp(i,name)==0): print "Phone number= ",phonebook[i] f=1 if (f==0): print "Given name not exist" Output Enter total number of friends 2 enter name: Prajwal enter phone number: 23456745 enter name: Sunny enter phone number: 45678956 2. Write a program to input ‘n’ employee number and name and to display all employee’s information in ascending order based upon their number. Code empinfo=dict() n=input("Enter total number of employees") i=1 while i<=n: a=raw_input("enter number") b=raw_input("enter name") empinfo[a]=b i=i+1 l=empinfo.keys() l.sort() print "Employee Information" print "Employee Number",'t',"Employee Name" for i in l: print i,'t',empinfo[i] 3. Write the output for the following Python codes. A={1:100,2:200,3:300,4:400,5:500} print A.items() print A.keys() print A.values()
  • 19. Python List Tuple & dictionary Prof. K. Adisesha| 19 Output [(1, 100), (2, 200), (3, 300), (4, 400), (5, 500)] [1, 2, 3, 4, 5] [100, 200, 300, 400, 500] 4. Write a program to create a phone book and delete particular phone number using name. Code phonebook=dict() n=input("Enter total number of friends") i=1 while i<=n: a=raw_input("enter name") b=raw_input("enter phone number") phonebook[a]=b i=i+1 name=raw_input("enter name") del phonebook[name] l=phonebook.keys() print "Phonebook Information" print "Name",'t',"Phone number" for i in l: print i,'t',phonebook[i] Write a program to input total number of sections and class teachers’ name in 11th class and display all information on the output screen. Code classxi=dict() n=input("Enter total number of section in xi class") i=1 while i<=n: a=raw_input("enter section") b=raw_input ("enter class teacher name") classxi[a]=b i=i+1 print "Class","t","Section","t","teacher name" for i in classxi: print "XI","t",i,"t",classxi[i]