UNIT IV LISTS TUPLES DICTIONARIES Prepared By M
UNIT - IV LISTS, TUPLES, DICTIONARIES Prepared By M. Ramkumar AP/CSE KIOT
Data Structure �Data structure defines a way of storing and organizing data in a computer �It is a group of data elements that are put together under one name
Sequence �Sequence is an object that contains multiple items of data �The items are stored in a sequence of one after another �In the sequence, each element has a specific index
Types of Sequence �There are different types of sequences in python includes the following: ◦ Lists ◦ Tuples ◦ Dictionaries
LISTS �A list is a mutable ordered sequence of objects ◦ Mutable – value of the elements in the list can be changed �It is a versatile data type �It is a sequence in which elements are written as a list of comma-separated values between square brackets �Element – an item in a list
Creating a list �List_variable = [ element 1, element 2, element 3, …. . ] �Examples: ◦ ◦ list_A = [1, 2, 3, 4, 5] list_B = [‘a’, ‘b’, ‘c’, ‘d’] list_C = [“good”, “going”] List_D = [1, ‘a’, “good”]
Lists - Indexing �Index is a number which specifies the position of the elements in the list �The index value starts from zero and automatically incremented by one for the next element in the sequence �The index for the first element in the list is 0 and for the last element is n-1 �Example: list_A = [1, 2, 3, 4, 5] ◦ ◦ ◦ list_A[0] = 1 list_A[1] = 2 list_A[2] = 3 list_A[3] = 4 list_A[4] = 5
Lists – Negative Indexing �Negative index identifies the elements from the end of the list �-1 represents the last element in the list �-2 represents the second last element in the list and so on �The negative index for the first element in the list is –n and for the last element is -1 �Example: list_A = [1, 2, 3, 4, 5] ◦ ◦ ◦ list_A[-1] = 5 list_A[-2] = 4 list_A[-3] = 3 list_A[-4] = 2 list_A[-5] = 1
Lists - print() �Syntax: print(list_name) �Examples: print(list_A) print(list_B) print(list_C) print(list-D) �Output: [1, 2, 3, 4, 5] [‘a’, ‘b’, ‘c’, ‘d’] [“good”, “going”] [1, ‘a’, “good”]
List - Mutable Example: list_A = [ 1, 2, 3, 4, 5] list_A[2] =30 print(list_A) �Now the elements in the list are ◦ [1, 2, 30, 4, 5]
Lists - Slicing �Slicing is used when you need a sub-list from a list �Slice is a span of elements that are taken from a sequence �Format for slicing : list_A[start : stop : step] �start – the starting position of the list �stop – the ending position of the list �step – the index value is incremented by the value given in the step
Lists - Slicing �list_A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] �print(list_A[: : 1]) //1, 2, 3, 4, 5, 6, 7, 8, 9, 10 �print(list_A[: : 2]) //1, 3, 5, 7, 9 �print(list_A[1: : 2]) //2, 4, 6, 8, 10 �print(list_A[1: 5]) //2, 3, 4, 5
Updating elements in the list �A list can be updated with the following operations: ◦ Inserting a new element in the list ◦ Appending an element at the end of the list ◦ Deleting/removing an element from the list
Updating elements in the list Method Description Syntax insert() To insert an element in the specified index of the list_A. insert(index, element) append() To add an element at the end of the list_A. append(elemen t) remove() To remove / delete the element from the list. If multiple copies of element present in the list then the first value will be deleted list_A. remove(elemen t) delete() The element in the index range will be deleted del list_A[2: 5] pop() Removes the element at the specified index. But index is an optional parameter. If the index is not specified then the last element in the list will be deleted list_A. pop(2) list_A. pop()
Example Program li=[10, 20, 30, 40, 50, 60, 70] print(li) li. append(80) print(li) li. insert(5, 20) print(li) li. remove(20) print(li) li. pop(1) print(li) li. pop() print(li) del li[1: 3] print(li) del li print(li) Output: [10, 20, 30, 40, 50, 60, 70] [10, 20, 30, 40, 50, 60, 70, 80] [10, 20, 30, 40, 50, 20, 60, 70, 80] [10, 40, 50, 20, 60, 70] [10, 20, 60, 70] //No elements in the list to print
Nested Lists �Nested lists means a list with in another list �Example: list_A=[1, 2, 3, 4, [10, 20], 5, 6] ◦ ◦ ◦ ◦ list_A[0] = 1 list_A[1] = 2 list_A[2] = 3 list_A[3] = 5 list_A[4] = [10, 20] list_A[5] = 5 list_A[6] = 6
Nested Lists �In order to print the element in the nested list, we need to use two indices �First index – represents the index in the main list �Second index – represent the index in the nested list �list_A[4, 0]=10 �list_A[4, 1]=20
Lists Methods Description Syntax count() Counts the number of times an element present in the list_A. count(elemen t) index() Return the lowest index of an element in the list. Gives a Value. Error if the element is not found in the list_A. index(5) reverse() It reverse the elements in the list_A. reverse() sort() Sorts the elements in the list in ascending ordedr list_A. sort() extend() Adds the elements of one list to he end of another list_A. extend(list_B)
Example Program a 1=[10, 20, 30, 40, 20] a 2=[50, 60, 70, 80, 70] c=a 1. count(20) print( c ) i=a 2. index(70) print(i) a 1. reverse() print(a 1) a 1. sort() print(a 1) a 1. extend(a 2) print(a 1) Output: // 2 // [20, 40, 30, 20, 10] // [10, 20, 30, 40] //[10, 20, 30, 40, 50, 60, 70, 80, 70]
Lists - Operations Operation length Description Example Returns the length of the len(list_A) list Output 5 Concatenat Joins two list ion + is used for concatenation list_A + list_B [1, 2, 3, 4, 5, ‘a’, ‘b’, ‘c’, ‘d’] Repitition Repeats the elements in the list * is used for repetition list_A*2 [1, 2, 3, 4, 5, 1, 2, 3, 4, 5] in Returns True if the element is present in the list a=bool(a) a=3 in list_A print a True not in Returns True if the element is not in the list a=bool(a) a=8 in list_A print a True
Lists - Operations Operation Description Example Output max Returns the maximum element in the list print(max(list_A)) 5 min Returns the minimum element in the list print(min(list_A)) 1 sum Adds the elements in the list print(sum(list_D)) which are numbers and return the sum 3 all Returns True if all the elements of the list are nonzero or if the list is empty A=[0, 1, 2] B=[] print(all(A)) print(all(B)) Fals True any Returns True if any one the elements in the lists is nonzero. If the list is empty then return False A=[0, 1, 2] B=[] print(all(A)) print(all(B)) True False
Lists - Operations Operation Description Example Output list Converts an iterable object (tuple, dictionary, set, string) to a list A=list(“KIOT”) [‘K’, ‘I’, ‘O’, ‘T’] print(A) sorted Returns a new sorted list. But the original list is not sorted. A=[5, 1, 3, 2, 4] B=sorted(A) print(B) [5, 1, 3, 2, 4] [1, 2, 3, 4, 5]
Lists - Aliasing �A 1=[10, 20, 30, 40, 50] �A 2=A 1 �When one list is assigned to another list using ‘=’, then new copy of the list is not created. �Both the lists point to the elements of one list in the memory. �This is known as “ALIASING”.
Lists - Aliasing A 1=[10, 20, 30, 40, 50] A 2=A 1 A 2[2]=25 print(A 1) �Two lists A 1& A 2 points to the same memory location. So any changes made in one list will reflect in the another. Hence, the result is [10, 25, 40, 50]. �Note: An alias is an another name for a variable. An alias happens when one variable’s value is assigned to another variable.
Lists - Cloning �If one want to modify a list and also keep a copy of the original list, then one should create a separate copy of the list. This process is called cloning. �The slice operation is used to clone a list.
Cloning - Example a = [81, 82, 83] b=a # creating a reference print(a==b) print(a is b) b = a[: ] # make a clone using slice print(a == b) Outputprint(a is b) True b[0] = 5 True print(‘List a=’, a) False print(‘List b=’, b) List a=[81, 82, 83] List b=[5, 82, 83]
Looping in Lists �for �enumerate() �range() �iterator()
for loop in Lists �for loop is used to access the elements in the list Example: list_A=[1, 2, 3, 4, 5] for i in list_A: print(i) Output: 1, 2, 3, 4, 5 Explanation: The value of an elements in the lists is stored in the variable i till the end of the list is reached.
enumerate() �This function is used to print both the index and value of the elements in the list �enumerate() returns index and value of the element as a tuple Example: list_A=[1, 2, 3, 4, 5] for index, i in enumerate(list_A): print(“list_A[”, index, “]=”, i) Output: 1 ist_A[0]=1 1 ist_A[1]=2 1 ist_A[2]=3 1 ist_A[3]=4 1 ist_A[4]=5
range() �In order to print the index of the elements, range() will be used Example: list_A=[1, 2, 3, 4, 5] for i in range(len(list_A)): print(“index: ”, i) Output: index: 0 index: 1 index: 2 index: 3 index: 4
range() �The value of i starts from zero and is incremented by one. The index value also starts from zero. Hence i represents the index value. If the value of i is less than the length of the list then the value of i will be printed.
iterator() �Iterator is used to loop over the elements of the list �Iterator fetches the initial value from the list �If it is used with next methods, then it automatically points to the next element in the list ◦ Syntax: variable_name = iter(list_name) �Iterator loop can be used with in a single for
Iterator - Example a=[1, 2, 3, 4, 5] it=iter(a) for i in range(len(a)): print("a[", i, "]=", next(it)) Outputa[0]=1 a[1]=2 a[2]=3 a[3]=4 a[4]=5
Filter() �The filter() function constructs a sequence that contains items from another sequence for which a function returns True. �If the sequence is a string, Unicode or a tuple, then the result will be of same type; otherwise it is always a list. �Syntax: filter(function, sequence)
filter() - Example def check(x): if(x%2==0): return 1 A=list(filter(check, range(1, 20))) print(A) Output: [2, 4, 6, 8, 10, 12, 14, 16, 1 8]
Map() �The map() function applies a particular function to every element of the list �Syntax: map(function , sequence) �After applying the specified function, the map() function returns the modified list �One can pass more than one sequence in the map() function ◦ The function must have as many arguments as there are sequences ◦ Each argument is called with the corresponding item from each sequence
Map() -Examples def add(x): x+=2 return x a=[1, 2, 3, 4, 5] print(“list a: ”, a) b=list(map(add, a)) print(“list b: ”, b) def add(x, y): return x+y a=[1, 2, 3, 4, 5] b=[6, 7, 8, 9, 10] c=list(map(add, a, b)) print(“Sum is ”, c) Output: list a: [1, 2, 3, 4, 5] List b: [3, 4, 5, 6, 7] Output: Sum is [7, 9, 11, 13, 15]
Reduce() �The reduce() function returns a single value to the calling function �It process the first two items of the sequence, then on the result and the next item and so on �Syntax: reduce(function, sequence)
reduce() - Example import functools def add(x, y): return x+y a=[1, 2, 3, 4, 5] print(“Sum = ”, end=“ “) print(functools. reduce(add, a)) Output: Sum = 15
List Comprehension �List comprehension is a construct that allows sequence to be built from other sequences �A list comprehension consists of ◦ An Input sequence ◦ A variable representing the members of the input sequence ◦ An output expression – produce a new list from the input sequence that satisfy the predicate ◦ An optional predicate expression
List Comprehension Syntax. List = [expression for variable in sequence] Example 1 cubes=[i**3 for i in range(6)] print(cubes) Output[0, 1, 8, 27, 64, 125] Example 2 print( [ (x, y) for x in [10, 20, 30] for y in [30, 10, 40] if x!=y ] ) Output[(10, 30), (10, 40), (20, 30), (20, 10), (20, 40), (30, 10), (30, 40)]
Tuple �Tuple is a sequence of immutable objects ◦ This means that you cannot change the values in tuple �Tuple use parentheses ( ) to define its elements �Syntax to create tuple: ◦ tuple_name=(val 1, val 2, …. )
Tuple - Examples tup 1=(1, 2, 3, 4, 5) print(tup 1) tup 2=(1. 1, 2. 2, 3. 3, 4. 4, 5. 5) print(tup 2) tup 3=(‘a’, ‘b’, ‘c’, ‘d’) print(tup 3) tup 4=(“abc”, “def”, “ghi”) print(tup 4) tup 5=(1, 1. 1, ‘a’, “bcd”) print(tup 5) Output: (1, 2, 3, 4, 5) (1. 1, 2. 2, 3. 3, 4. 4, 5. 5) (‘a’, ‘b’, ‘c’, ‘d’) (“abc”, “def”, “ghi”) (1, 1. 1, ‘a’, “bcd”)
Tuple Assignment �Any set of multiple comma-separated values written without an identifying symbol like brackets() are also treated as tuple by default Example: a= (10, 20) print(a) tup=(100, 200) x, y=tup print(x, y) Output: 10 20 100 200
Tuple �If you wan to create a tuple with a single element, then you must add a comma after that element �If you didn’t specify the comma then the element is treated as an ordinary data type Example 1: tup =(10, ) print(type(tup)) Example 2: tup =(10) print(type(tup)) Output: <type ‘tuple’> Output: <type ‘int’>
Accessing Values in Tuple �Index is used to access the values in the tuple �Slice and concatenation can be done in tuple Output: Example: tup[2: 4]=(3, 4) tup[: 4]=(1, 2, 3, 4) tup=(1, 2, 3, 4, 5, 6, 7, 8) print(“tup[2: 4]=”, tup[2: 4]) tup[4: ]=(5, 6, 7, 8) tup[: ]=(1, 2, 3, 4, 5, 6, 7, print(“tup[: 4]=”, tup[: 4]) 8) print(tup[4: ]=”, tup[4: ]) print(“tup[: ]=”, tup[: ])
Updating Tuple �Since tuple is immutable, we can only extract values from tuple to form another tuple Example: tup 1=(1, 2, 3, 4) tup 2=(5, 6, 7, 8) tup 3=tup 1+tup 2 print(tup 3) Output: (1, 2, 3, 4, 5, 6, 7, 8)
Deleting Elements in Tuple �Since tuple is immutable, you cannot delete a value from the tuple, but you can delete the entire tuple by using del statement Example: tup=(1, 2, 3, 4) del tup[2] #Type Error: Tuple does not support item deletion del tup print(tup) #name tup is not defined
Basic Tuple Operations Operation Expression Output Length – returns the length of the tuple tup=(1, 2, 3, 4, 5) print(len(tup)) 5 Concatenation – combines two tuples and store it in another tuple tup 1=(1, 2, 3, 4, 5) tup 2=(6, 7, 8, 9, 10) tup 3=tup 1+tup 2 print(tup 3) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) Repetition – repeat the elements of the tuple tup=(1, 2, 3) print(tup*2) (1, 2, 3, 1, 2, 3) Membership (in) tup=(1, 2, 3, 4, 5) print(3 in tup) True Maximum (max) – returns the maximum element in the tuple tup=(1, 2, 3, 4, 5) print(max(tup)) 5 Minimum (min) – returns the tup=(1, 2, 3, 4, 5) minimum element in the print(tup) 1
Basic Tuple Operations Operation Iteration Comparison Expression tup=(1, 2, 3, 4, 5) for i in tup: print(i, end=“ ”) tup 1=(1, 2, 3, 4, 5) tup 2=(1, 2, 3, 4, 5) print(tup 1>tup 2) A=tuple(“Hello”) Convert to a tuple print(A) index() tup=(1, 2, 3, 4, 5, 6) tuple. print(tup. index(4)) Index(element) count() tup =(1, 2, 3, 4, 2, 5, 2) print(tup. count(2)) Output 12345 False (‘H’, ‘e’, ‘l’, ‘o’) 3 3
Tuples for Returning Multiple Values �A function can return more than one value in the form of tuple Example: Output: def maxmin(mark) : Highest & Lowest Mark is (99, x=max(mark) y=min(mark) 76) <class 'tuple'> return (x, y) mark=(90, 87, 96, 76, 99, 84) x=maxmin(mark) print(“Highest & Lowest Mark is ", x) print(type(x))
Nested Tuples �One can define a Tuple inside another tuple Example: students=((“Arav”, “BE”), (“Raja”, “MBA”), (“Kalai”, “MCA”)) for i students: print(i) Output: (“Arav”, “BE”) (“Raja”, “MBA”) (“Kalai”, “MCA”)
Tuple Comprehension �Tuple comprehension is a construct that allows sequence to be built from other sequences Example: Output: Original Tuple (1, 2, 3, 4, 5) def double(T): Double values (2, 4, 6, 8, 10 return ([i*2 for i in T]) tup=1, 2, 3, 4, 5 print(“Original Tuple”, tup) print(“Double Values”, double(tup)) Note: If you did not specify parenthesis for the values, then it is automatically treated as tuple.
Variable Length Argument Tuples � Variable length argument begins with * symbol and is known as gather – all the values are stored in the form of tuple � Opposite of gather is scatter – the values in the tuple are scattered pass as an individual element Example: tup=(56, 3) q, r = divmod(*tup) print(q, r) Output: 18 2 Note: If you did not specify * before tuple name then the tuple is treated as a single argument and report an error because divmod() function requires two arguments.
zip() function �It takes two or more sequences and zips them into a list of tuples �The tuple formed has one element from each sequence Example; tup=(1, 2, 3, 4, 5) list=(‘a’, ‘b’, ‘c’, ‘d’, ‘e’) print(list( zip(tup, list))) Output: [(1, ‘a’), (2, ‘b’), (3, ‘c’), (4, ‘d’), (5, ‘e’)]
Difference between List and Tuple List is represented in [] List is mutable Elements of List can be changed Tuple is represented in () Tuple is immutable Elements of tuple cannot be changed More built in functions are available to manipulate list Eg: L=[1, 2, 3, 4, 5] L[0]=100 print(L) O/P : [100, 2, 3, 4, 5] Less built in functions are available to manipulate list Eg: T=(1, 2, 3, 4, 5) T[0]=100 print(T) O/P : Error
Dictionary �Dictionary is a data structure in which we store values as a pair of key and value. �Each key is separated from its value by a colon (: ) �Consecutive items are separated by commas. �The entire items in a dictionaries are enclosed in curly brackets {}.
Dictionary Syntax: dictname = {key_1: value_1, key_2: value_2, key_3: value_3} Creating empty dictionary: dict_name = { }
Accessing Values �To access the value in the dictionary, need to give the key value in the index �dict_name[‘key’] or dict_name [“key”] will return the corresponding value of keyvalue pair Example: D= {‘Roll_No’ : ’ 17 EC 001’ , ‘course ‘ : ’BTech’ } print ( D[‘ Roll_No ‘] ) print ( D[‘ Name ‘ ] ) print ( D[‘ course ‘ ] ) Output: 17 EC 001 Arav BTech ‘Name’ : ‘Arav ’ ,
Collision �If you try to access the key which is not in the dictionary then a key error is generated �This is known as collision Example: D = {‘Name’: ’Arav’} print (D [‘Marks ‘ ]) Output: Key error: Traceback (most recent call last): File “C: Phython 34 Try. py”, line 2, in <module> print D [‘Marks’]
Updating Values in Dictionary �Inserting a new key-value pair �Can change / update the value of a key-value pair �Can delete a key-value pair
Insertion Example: D = {‘Roll_No’ : ’ 17 EC 001’ , ‘Name’ : ‘Arav ’, ‘course ‘ : ’BTech’ } D[‘GPA’]=8. 45 print(D) Output: {'Roll_No': '17 EC 001', 'Name': 'Arav', 'course': 'BTech', 'GPA': 8. 45}
Updation Example: D = {‘Roll_No’ : ’ 17 EC 001’ , ‘Name’ : ‘Arav ’, ‘course ‘ : ’BTech’ } D[‘GPA’]=8. 45 print(D) D[‘course’]=‘BE’ print(D) Output: {'Roll_No': '17 EC 001', 'Name': 'Arav', 'course': 'BTech', 'GPA': 8. 45} {'Roll_No': '17 EC 001', 'Name': 'Arav', 'course': 'BE', 'GPA': 8. 45}
Deletion �To delete one or more items Using del keyword �To delete one or more items is just one statement, use the clear () function. �We can also use pop() method to delete the particular key �del Syntax: del dict_name[‘Key’] �clear() Syntax: dict_name. clear()
del and clear() Example: D = {'Roll_No' : '16/001' , 'Name' : 'Arav' , 'course': 'BE' } del D[ 'course'] # delete the key-value pair print ("After deleting course : ", D ) D. clear() #deletes all key-value pairs print(D) D = {'Roll_No' : '16/001' , 'Name' : 'Arav' , 'course': 'BE' } del D #delete the entire dictionary print(D) Output: After deleting course : {'Roll_No': '16/001', 'Name': 'Arav'} {}
pop() Method � In general pop() function returns the key-value pair which is to be popped our from the dictionary � Syntax: dict. pop(‘key’) - deletes the key-value pair in the dictionary and returns the key-value pair � Syntax: dict. pop(‘key’, default. Value) – If the key is not in the dictionary then it returns the default value given in the function � Syntax: dict. popitem() - It deletes a key-value pair randomly in the dictionary and return that key-value pair
pop() - Example: D = {‘Roll_No’ : ‘ 16/001’ , ‘Name’ : ‘Arav ’ , ‘course ‘ : ’BTech’ } print ( “Name is : ” , D. pop(‘Name’)) # return Name print(“Dictionary after popping Name is : “ , D) print ( “ Mark is: ” , D. pop (‘Mark’ , -1)) # return default value print(“Dictionary after popping Marks is : ”, D ) print (“ Randomly popping any items : ”, D. popitem()) print (“Dictionary after Random popping is : ” , D) print(“Aggregate is : “ , D. pop(‘ Aggr ’)) # generates error print (“Dictionary after popping Aggregate is : ” , D )
pop() - Example Output: NAME is : Arav Dictionary after popping Name is : { ‘course ’ : ‘BTech’, ‘Roll_No’ : ‘ 16/001’ } Marks is : -1 Dictionary after popping Marks is : { ‘course ‘ : ’BTech’, ‘Roll_No’: ‘ 16/001’ } Randomly popping any items : { ‘course ’: ‘BTech’} Dictionary after Random popping : { ‘Roll_No’ : ‘ 16/001’ } Traceback (most recent call last): File “C: Phython 34 Try. py”, line 8, in <module> print(“Aggregate is : “ , D. pop(‘ Aggr ’)) Key. Error: ‘Aggr’
Dictionary Comprehension It creates a new dictionary from the given sequence. Syntax: {key : expression for key in sequence condition} Example: D= { X : 2 *X for X in range (1, 5)} print (D) Output: { ‘ 1’: 2, ‘ 2’: 4, ‘ 3’: 6, ‘ 4’: 8 }
Sorting Items in Dictionary Sorted() is used to sort the dictionary based on keys or values It returns the result as list Example 1: d={"Roll": "01", "Name": "Anbu", "Course": "CSE"} print(sorted(d. keys())) Output: ['Course', 'Name', 'Roll']
Sorting Items in Dictionary Example 2: d={"Roll": "01", "Name": "Anbu", “Course": "CSE" } print(sorted(d. values())) Output: ['1', 'Anbu', 'CSE']
Looping over Dictionary Looping is used to access only values or only keys or both keys and values Example 1: d={'Roll': "1", "Name": "Anbu", "Course": "CSE"} for keys in d: (or) for keys in d. keys(): print(keys) � Output: Roll Name Course
Looping over Dictionary Example 2: d={'Roll': "1", "Name": "Anbu", "Course": "CSE"} for val in d. values(): print(val) Output: 1 Anbu CSE
Looping over Dictionary Example 3: dic={'Roll' : "1", "Name" : "Anbu", "Course" : "CSE"} for key , val in dic. items(): print(key , val) Output: Roll 1 Name Anbu Course CSE
Nested Dictionary A dictionary within another Dictionary is called nested dictionary Example 1: d={'arthi' : {'phy': '90', 'python': '89'}, 'balu': {'phy': '80', 'python': '76'} } for key, val in d. items(): print(key, val) Output: arthi {'phy': '90', 'python': '89'} balu {'phy': '80', 'python': '76'}
Built-in Dictionary Functions and Methods d={"Roll": 01, "Name": "Anbu", "Course": "CS E"} Operation Description Example Output len(d) Returns the length of the dictionary print(len(d)) str(d) It converts all the print(type elements of dictionary (str(d["Roll"]))) to string d. clear() It clears all entries in dictionary print(d. clear()) 3 <class 'str'> None
Dictionary Methods Name Description fromkeys(seq[, Create a new dictionary val]) with keys from seq and value set to val, If no value is specified none is assigned as default value d. get(key) Returns the value for key which is passed as an argument d. has_key(key) Returns true if key is present in dictionary else returns false Example d = {'cse', 'eee', 'ece'} x=dict. fromkeys(d, 1 ) print(x) Output {'eee': 1, 'ece': 1, 'cse': 1} d={"Roll": 1, "Name": "Anbu"} print(d. get("Name")) Anbu d={"Roll": 1, "Name": "Anbu"} print("Name" in d) print("course" in d) True False
Dictionary Methods Name Description Example Output d. copy() Returns a shallow copy of the dictionary (ie) the dictionary returned will not have a duplicate copy of dictionary but have the same reference d 1 = {"Roll" : 1, "Name": "Anbu"} d 2=d 1 d 2['Name']= 'Kavi' print('d 1: ' , d 1) print('d 2: ' , d 2) d 1: {‘Roll’ : 1, ‘Name’ : ‘Kavi’} d 2: {‘Roll’ : 1, ‘Name’ : ‘Kavi’ } d. setdefault(k Sets a default value for ey, value) a key that is not present in the dictionary d={"Roll": 1, "Name": "Anbu"} d: {‘Roll’ : 1, d. setdefault("Mark", 9 ‘Name’ : ‘Anbu’, 0) ‘Mark’: 90} print(d) d. items() d={"Roll": 1, "Name": "Anbu"} for i, j in d. items(): print(i, j) Used to iterate through items in a dictionary Roll 1 Name Anbu
Dictionary Methods Name Description Example Output d. update(d 2) Adds the key value pairs of d 2 to d 1 = {"Roll" : 1, "Name": "Anbu"} d 2 = {"GPA" : 9. 3, "Class": "FC"} d 1. update(d 2) print(d 1) d 1: {‘Roll’ : 1, ‘Name’ : ‘Anbu’, ‘GPA’ : 9. 3, ‘Class’ : ‘FC’} Checks whether the given key is present in dictionary or not d={"Roll": 1, "Name": "Anbu"} print("Name" in d) print("GPA" in d) in not in True False
String Formatting � String formatting is allowed in dictionary � (ie) %d %f %s can be used for integer, floating point number and string etc Example: d={"Anbu": "BE", "Kavi": "Btech"} for k, v in d. items(): print("%s is studying %s" %(k, v)) Output: Anbu is studying BE Kavi is studying BTech
Difference between List and Dictionary S. No LISTS DICTIONARY 1. List is an ordered set of items Dictionary is a data structure with key-value pair 2. List uses index to access the elements in the list and the index is a number In dictionary any type of data can be used as index but it is a string (key) 3. Lists are used to look up a value Dictionary is used to take one value and look up another value. So dictionary is also known as lookup table
Illustrative Examples �Selection Sort �Insertion Sort �Merge Sort �Histogram
- Slides: 82