Full Transcript

Academic year 2024-25 (NEP) Sathaye College BSc IT SEM III Python Programming Syllabus Unit 2 String- Strings are immutable, String slicing, String operations- concatenation, repetition, appending, comparison,Traversing with loop, Built-in functions and methods List- List are mutable, creating list,...

Academic year 2024-25 (NEP) Sathaye College BSc IT SEM III Python Programming Syllabus Unit 2 String- Strings are immutable, String slicing, String operations- concatenation, repetition, appending, comparison,Traversing with loop, Built-in functions and methods List- List are mutable, creating list, access and update values in list, deleting list and list elements, cloning list, nested lists, List operations, List methods, List comprehension, Looping in list Tuples- Tuples are immutable, creating tuple, access and update values in tuple, deleting tuple and tuple elements, tuple assignment, tuple for returning multiple values from function, nested tuples, variable length argument tuple, tuple vs list Dictionary- Creating dictionary,properties of dictionary keys, accessing values in dictionary, adding and modifying an item in dictionary,deleting elements from a dictionary, sorting, looping over dictionary, nested dictionaries, built in dictionary methods and functions Set- Creating set, various set operations using built in methods and functions String A string is a sequence of characters. we can access the characters one at a time with the bracket operator. s=“welcome” letter=s this gives character ‘w’ The expression in brackets is called an index >>>letter w The value of index must be an integer letter=s[1.5] ……this is not correct len() function- len is a built-in function that returns the number of characters in a string >>>s=“welcome” >>>len(s) 7 What happens if you try this… >>>length=len(s) >>>last=s[length] >>>last In the previous code we get index error. We start index with 0, so for 7 letter word the range of the indices is 0 to 6 To get the last character, >>>length=len(s) >>>last=s[length -1] In string we can use negative indices, which count backward from the end of the string Negative indices starts with -1 s[-1] gives the last letter of the string s[-2] gives the second last letter of the string String Traversal with loop A lot of computations involve processing a string one character at a time. Often, they start at the beginning, select each character in turn, do something to it, and continue until the end. This pattern of processing is called a traversal. We can use while and for loop for traversal. Example – string traversal with while loop and for loop index=0 s ="welcome" print("traversal with while loop") while index < len(str): letter=s[index] print(letter) index=index+1 print("traversal with for loop") for letter in s: print(letter) output- traversal with while loop w e l c o m e traversal with for loop w e l c o m e String Slices A segment of a string is called slice. Selecting a slice is similar to selecting a character. s=“hello everyone” s[0:5] gives hello s[6:14] gives everyone If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string s[:2] ……? s[6:] ……. ? If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks: >>>s[2:2] ‘’ An empty string contains no characters and has length 0 Now try this….. s=“welcome” s[:] Output… Welcome Check your string slices concept : s='python programming' >>> s[1:] 'ython programming' >>> s[:] 'python programming' >>> s[:5] 'pytho' >>> s[-1:] 'g' >>> s[-5:] 'mming' >>> s[-19:] 'python programming' >>> s[-10:-3] 'rogramm' >>> s[4:10] 'on pro' >>> s[:-1] 'python programmin' >>> s[:0] '' >>> Immutable - strings are immutable, which means you can’t change an existing string. s=“hello everyone” s=‘j’ This gives error. The best you can do is create a new string that is a variation on the original >>>s =“hello everyone” >>>greeting=‘j’ + s[1:] >>>greeting jello everyone This has no effect on the original string Searching- The pattern of computation—traversing a sequence and returning when we find what we are looking for—is called a search. Look at the next program… Searches for a character in each string and return index number else returns -1 #string_searching.py def find(word, letter): index = 0 while index < len(word): if word[index] == letter: return index index = index + 1 return -1 w="welcome to python programming" l=input("enter the character to be searched ") print("if the character is found, it will give index number ") print("if the character is not found, it will return -1") print(find(w,l)) Output– 1st run >>> enter the character to be searched w if the character is found, it will give index number if the character is not found, it will return -1 0 2nd run-- >>> enter the character to be searched m if the character is found, it will give index number if the character is not found, it will return -1 5 3rd run-- >>> enter the character to be searched z if the character is found, it will give index number if the character is not found, it will return -1 -1 Note—modify the program on previous slide after learning list data type of python. Program should search for a character in a given string and should give index numbers of a character (multiple occurrence) Looping and counting word = 'banana' count = 0 for letter in word: if letter == 'a’: count = count + 1 print(count) Output … 3 This program demonstrates another pattern of computation called a counter. Encapsulate the previous code in a function named cnt() and generalize it so that it accepts the string and the letter as arguments #string_count.py def cnt(word, letter): count = 0 for i in word: if i == letter: count = count + 1 return count w=input("enter the word --") l=input("enter the letter --") print("the letter " +l+ " appears " +str(cnt(w,l))+ " times") Output… enter the word-- hello everyone enter the letter -- e the letter e appears 4 times String methods s.capitalize() -- Capitalizes first character of s s.title() --Capitalizes first letter of each word in s s.count(sub)-- Count number of occurrences of sub in s s.find(sub)-- Find first index of sub in s, or -1 if not found s.lower()-- Convert s to lower case s.upper() – Converts s to upper case s.index(sub)-- Find first index of sub in s, or raise ValueError if not found s.rfind(sub)-- Same as find, but last index s.rindex(sub)-- Same as index, but last index s.replace(old, new) --Replace all instances of old with new in string Assume s is string with content ‘welcome to python programming’ >>> s.replace('python', 'c++') 'welcome to c++ programming’ ‘separater’.join(lst)-- Join a list of words(lst) into a single string with ‘separater’ replaced by actual separator character. >>> l=['ab','xy', 'pq’] >>> ':'.join(l)`#here ‘:’ is a separator 'ab:xy:pq' find() method The find method is more general. It can find substrings, not just characters. If found, gives index number. If not found, returns -1. By default, find starts at the beginning of the string, but it can take a second argument, the index where it should start. s=“banana” s.find(‘a’) gives index 1 s.find(‘na’) gives index 2 s.find(‘na’,3) gives index 4 Find can also take the optional third argument, the index where it should stop s.find(‘n’,0,1) what will be output? Ans---- -1 >>> s="banana" >>> s.count('a') 3 >>> s.index('a') 1 >>> s.rindex('a') 5 >>> s.capitalize() 'Banana' >>> s.rfind('a') 5 >>> s.lower() 'banana' >>> s="welcome to python programming" split()---Splits String into words and returns list >>> s.split() ['welcome', 'to', 'python', 'programming’] >>> s1=" happy Diwali " >>> s1 ' happy Diwali ‘ strip()----Removes Both Leading and Trailing Characters >>> s1.strip() 'happy Diwali' isalnum, isalpha, isdigit, istitle, isupper, islower, lstrip, rstrip try yourself---- format() method-- We can combine strings and numbers by using the format() method. The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are: age = 36 txt = “My name is Rahul, and I am {}” print(txt.format(age)) ‘in’ operator and string The word ‘in’ is an operator that takes two strings and returns True (Boolean value) if the first string appears as a substring in the second string. >>> 'come' in 'welcome' True >>> 'go' in 'welcome' False What this function is doing? >>> def in_both(word1, word2): for letter in word1: if letter in word2: print(letter) >>> in_both('happy', 'hary') h a y >>> String comparison The relational operators work on strings ==, < , >. Uppercase and lowercase letters are not same. All the uppercase letters come before all the lowercase letters. So normally before comparison covert the strings to a standard format such as lowercase letters e.g of relational operator on string if w1 == w2: print (“words are equal”) String operations (concatenation and repetition) ‘+’ Operator performs string concatenation ‘*’ Operator performs string repetition >>> s1="happy" >>> s2="home" >>> s1+s2 'happyhome' >>> s1*3 'happyhappyhappy' >>> Deleting string del keyword is used to delete string. We cannot delete or remove characters from a string, but entire string can be deleted. str1=“happy” del str1 del str1 ------wrong List A list is a sequence of values. In a string, the values are characters. In a list, the values can be any type. The values in a list are called elements or sometimes items. There are several ways to create a new list; the simplest is to enclose the elements in square brackets [ ] [1,4,5,6] [1,’w’,’d’,3,1.5] A list within another list is nested. An empty list is represented as [] Accessing elements in list You can assign list values to variable. var=[1,3,4.5] To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. >>> list1=["maths", "chemistry", "biology"] >>> list1 ['maths', 'chemistry', 'biology'] >>> list1 'maths' >>> list1[1:] ['chemistry', 'biology'] >>> list1 Traceback (most recent call last): File "", line 1, in list1 IndexError: list index out of range List are mutable When the bracket operator appears on the left side of an assignment, it identifies the element of the list that will be assigned. >>> numbers = [42, 123] >>> numbers = 5 >>> numbers [42, 5] Mutable means you can change the original list by assignment. List indices work the same way as string indices: --Any integer expression can be used as an index. -- If you try to read or write an element that does not exist, you get an IndexError. --If an index has a negative value, it counts backward from the end of the list. ‘in’ operator on list in operator also works on lists list1=["maths", "chemistry", "biology"] 'maths' in list1 True >>> 'math' in list1 False Traversing a list Most common way is through for loop >>> list1=["maths", "chemistry", "biology"] >>> list1 ['maths', 'chemistry', 'biology'] >>> for i in list1: print(i) output- maths chemistry biology >>> This works if we want to read elements of list. But for update or write elements use indices. A common way to do that is to combine the built-in functions range and len---- >>> numbers=[2,4,5,12] >>> for i in range(len(numbers)): numbers[i]=numbers[i]*2 >>> numbers [4, 8, 10, 24] Deleting list and deleting element of list Delete list with del. >>> del list1 #where list1 is list, deletes entire list. Deleting elements of list. There are several ways to do this- pop, del, remove 1) pop(index) --- it modifies the list and returns the element that was removed If no index is provided, it deletes and returns the last element. >>> t = ['a', 'b', 'c'] >>> x = t.pop(1) >>> t ['a', 'c'] >>> x 'b' >>>t.pop() ‘c’ >>>t [‘a’] 2)del operator If you don’t need the removed value, you can use the del operator. >>> t = ['a', 'b', 'c'] >>> del t >>> t ['a', 'c’] 3) remove () If you know the element you want to remove (but not the index), you can use remove. >>> t = ['a', 'b', 'c'] >>> t.remove('b') >>> t ['a', 'c’] The return value from remove is None. To remove more than one element, you can use del with a slice index: >>> t = ['a', 'b', 'c', 'd', 'e', 'f'] >>> del t[1:5] >>> t ['a', 'f’] the slice selects all the elements up to but not including the second index list with * and + operator The + operator concatenates lists >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> c [1, 2, 3, 4, 5, 6] The * operator repeats a list a given number of times: >>> * 4 [0, 0, 0, 0] >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3] Objects and values a = 'banana' b = 'banana’ We know a and b refer to string, but we don’t know whether they refer to same string. There could be two possible states a -> ‘banana’ a b-> ‘banana’ b ‘banana’ In one case----a and b refer to two objects with same value in 2nd case---- a and b refer to same object ‘is’ operator To check whether two variables refer to the same object, you can use the is operator >>> a='banana' >>> b='banana' >>> a is b True In this case only one string object is created and a and b both refer to same string >>> a=[1,2,3] >>> b=[1,2,3] >>> a is b False In this case , we create two lists with two objects. In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are identical, they are also equivalent, but if they are equivalent, they are not necessarily identical. Aliasing If a refers to an object and you assign b = a, then both variables refer to the same object: >>> a = [1, 2, 3] >>> b = a >>> b is a True The association of a variable with an object is called a reference. In this example, there are two references to the same object. An object with more than one reference has more than one name, so we say that the object is aliased. If the aliased object is mutable, changes made with one alias affect the other. For immutable objects, there is no problem Aliasing for mutable objects >>> t=[1,2,3] >>> s=t >>> s is t True >>> s=4 >>> s [1, 2, 4] >>> t [1, 2, 4] It is better to avoid aliasing for mutable objects List methods and functions Functions--- 1) len(l1)--- gives the length of the list 2) max(l1)--- returns item from the list with max value 3) min(l1)--- returns item from the list with minimum value 4) list(sequence)--- converts into list >>> s='happy' >>> list(s) ['h', 'a', 'p', 'p', 'y'] Methods— 1) list.append(element) ---- appends element to list >>> z=[1,2,1,3,4,3,4,1] >>> z.append(6) >>> z [1, 2, 1, 3, 4, 3, 4, 1, 6] The append method modifies a list, but the + operator creates a new list. 2) list.count(element)--- Returns count of how many times element occurs in list 3) list.index(element)--- Returns the lowest index in list that element appears 4) list.insert(index,element) ---- Inserts element into list at offset index ------Try these index() and insert() methods during practical. append method modifies list >>> t1 = [1, 2] >>> t2 = t1.append(3) >>> t1 [1, 2, 3] >>> t2 None + operator creates new list >>> t3 = t1 + >>> t1 [1, 2, 3] >>> t3 [1, 2, 3, 4] 5) list.reverse()-- Reverses elements of list 6) list.sort() --- sorts the list 7) list.copy()--- returns a shallow copy of the list old_list = [1, 2, 3] new_list = old_list When new_list is modified then old_list also modified if you need the original list unchanged when the new list is modified, you can use copy() method. This is called shallow copy >>> list1 [3, 5, -4, 2, 1] >>> newlist1=list1.copy() >>> newlist1 [3, 5, -4, 2, 1] >>> newlist1.append(7) >>> newlist1 [3, 5, -4, 2, 1, 7] >>> >>> list1 [3, 5, -4, 2, 1] 8) list.extend() ---Appends the contents of another list list1.extend(list2) >>> list1 [3, 5, -4, 2, 1] >>> list2=[10,20] >>> list2 [10, 20] >>> list1.extend(list2) >>> list1 [3, 5, -4, 2, 1, 10, 20] >>> So what is the difference between append() and extend()?..... 9) list.clear()-- The clear() method removes all items from the list. >>> list2=[10,20] >>> list2 [10, 20] >>> list2.clear() >>> list2 [] >>> Things to remember about list-- Most list methods modify the argument and return None This is the opposite of the string methods, which return a new string and leave the original as it is…. word = word.strip() ---- this works (string) t = t.sort() ----- wrong, sort returns None (list) To add an element, you can use the append method or the + operator. Assuming that t is a list and x is a list element t.append(x) ---- correct t = t + [x] --- correct t += [x] --- correct Now tell what will happen for following commands----- t.append([x]) t = t.append(x) t=t+x and try to understand from error message/output If you want to use a method like sort that modifies the argument, but you need to keep the original list as well, you can make a copy. >>> t = [3, 1, 2] >>> t2 = t[:] #copy of original >>> t2.sort() >>> t [3, 1, 2] >>> t2 [1, 2, 3] Built in function sorted returns a new sorted list and leaves the original as it is. >>> t2 = sorted(t) >>> t [3, 1, 2] >>> t2 [1, 2, 3] We have done character searching earlier. Now we will modify this with list append() function. Program should search for a character in a given string and should give index numbers of a character (multiple occurrence) #string_searching modified.py def find(word, letter): index = 0 i=[] while index < len(word): if word[index] == letter: i.append(index) index = index + 1 print(i) w="welcome to python programming" l=input("enter the character to be searched ") print("if the character is found, it will give index numbers of the characters.") print("if not found empty list will be given ") find(w,l) Output— 1st run enter the character to be searched p if the character is found, it will give index numbers of the characters. if not found empty list will be given [11, 18] 2nd run-- enter the character to be searched w if the character is found, it will give index numbers of the characters. if not found empty list will be given 3rd run-- enter the character to be searched z if the character is found, it will give index numbers of the characters. if not found empty list will be given [] List comprehension Python List comprehension provides a much shorter syntax for creating a new list based on the values of an existing list. Python List Comprehension Syntax-- Syntax: newList = [ expression(element) for element in oldList if condition ] Parameter: expression: Represents the operation you want to execute on every item within the iterable. element: The term “variable” refers to each value taken from the iterable. iterable: specify the sequence of elements you want to iterate through.(e.g., a list, tuple, or string). condition: (Optional) A filter helps decide whether or not an element should be added to the new list. Return:The return value of a list comprehension is a new list containing the modified elements that satisfy the given criteria. Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name. Without list comprehension you will have to write a for statement with a conditional test inside: fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [] for x in fruits: if "a" in x: newlist.append(x) print(newlist) With list comprehension you can do all that with only one line of code: 1) fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruits if "a" in x] print(newlist) 2) Only accept items that are not "apple": newlist = [x for x in fruits if x != "apple"] The condition if x != "apple" will return True for all elements other than "apple", making the new list contain all fruits except "apple". 3) With no ‘if’ statement: newlist = [x for x in fruits] 4) You can use the range() function to create an iterable: newlist = [x for x in range(10)] 5) Accept only numbers lower than 5: newlist = [x for x in range(10) if x < 5] 6) Return "orange" instead of "banana": newlist = [x if x != "banana" else "orange" for x in fruits] Look at these three programs which gives same output- 1.Using for loop- numbers = [] for i in range(1, 6): numbers.append(i*10) print(numbers) 2.Using list compresension – numbers = [i*10 for i in range(1, 6)] print(numbers) 3.Using lambda function - numbers = list(map(lambda i: i*10, [i for i in range(1, 6)])) print(numbers) output for all programs is [10,20,30,40,50] Note- map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.) The filter() function returns an iterator where the items are filtered through a function to test if the item is accepted or not. Example- ages = [5, 12, 17, 18, 24, 32] def myFunc(x): if x < 18: return False else: return True adults = filter(myFunc, ages) for x in adults: print(x) output- 18 24 32 Tuples A tuple is a sequence of values. The values can be any type and are indexed by integers Tuples are immutable. Tuples are comma separated values. But common practice is to place these values in parentheses. >>> t=1,2,3.3,'r' >>> type(t) >>> t=(1,2,3.3,'r') >>> type(t) To create a tuple with a single element, you must include a final comma: >>> t1 = 'a', A value in parentheses is not a tuple: >>> t2='a', >>> type(t2) >>> t3=('a') >>> type(t3) >> t1=(3,5,6,2,5,1,7,8,8) >>> t1.count(8) 2 >>> t1.index(5) 1 How built in functions with tuple… 1) len()—Return the length (the number of items) in the tuple. 2)max()-- Return the largest item in the tuple. 3)min()-- Return the smallest item in the tuple. 4)sorted()-- Take elements in the tuple and return a new sorted list (does not sort the tuple itself). 5)sum()-- Retrun the sum of all elements in the tuple. 6) tuple()-- Convert an iterable (list, string, set, dictionary) to a tuple 7)all(iterable)--Return True if all elements of the tuple are true (or if the tuple is empty). Where iterable can be list, tuple, dictionary 8) any(iterable)-- Return True if any element of the tuple is true. If the tuple is empty, return False 9)enumerate()--- Return an enumerate object. It contains the index and value of all the items of tuple as pairs. Truth table for all() When Return Value All values are true True All values are false False One value is true (others are false) False One value is false (others are true) False Empty Iterable True # all values true l = [1, 3, 4, 5] print(all(l)) True # all values false l = [0, False] print(all(l)) False # one false value l = [1, 3, 4, 0] print(all(l)) False # one true value l = [0, False, 5] print(all(l)) False # empty iterable l = [] print(all(l)) True Truth table for any() When Return Value All values are true True All values are false False One value is true (others are false) True One value is false (others are true) True Empty Iterable False l = [1, 3, 4, 0] print(any(l)) True l = [0, False] print(any(l)) False l = [0, False, 5] print(any(l)) True l = [] print(any(l)) False Try all() and any() on tuple during practical----- enumerate()— enumerate(iterable, start=0) where iterable - a sequence start (optional) - enumerate() starts counting from this number. If start is omitted, 0 is taken as start. t1=(3,5,1,7,2) for i in enumerate(t1): print(i) Output--- (0, 3) (1, 5) (2, 1) (3, 7) (4, 2) t1=(3,5,1,7,2) for count, item in enumerate(t1,1): print(count, item) Output--- 13 25 31 47 52 Dictionaries A built-in data type. Python’s best feature. They are the building blocks of many efficient and elegant algorithms. It is like list but more general. Dictionaries are mutable. In a list, indices are integers but in dictionary indices are of any data type. A dictionary contains a collection of indices, which are called keys, and a collection of values. Each key associated with single value. The association of a key and a value is called a key-value pair or an item. Dictionary represents mapping from keys to values. So each key maps to a value. Function dict() creates empty dictionary. mydict=dict() {} {} represents empty dictionary Dictionaries are optimized to retrieve values when the key is known. Dictionary is an unordered collection of items this means the order of items in a dictionary is unpredictable. This is not a problem as elements of a dictionary are never indexed with integer indices. We use the keys to look up the corresponding values. Creating dictionaries 1) d={} type(d) 2) d=dict() type(d) 3) d={1:'a',2:'c',4:'f'} type(d) Accessing elements from a dictionary Two methods---- 1) using keys inside square brackets 2) using get() method >>> d={1:'a',2:'d',4:'r',6:'h'} >>> d 'a’ >>> d.get(2) 'd' Adding elements to a dictionary >>> d {1: 'a', 4: 'r', 6: 'h’} >>> d='t' >>> d {1: 'a', 4: 'r', 6: 'h', 3: 't’} d=‘z’ >>>d {1: 'z', 4: 'r', 6: ‘h', 3: ‘t’} Deleting elements from a dictionary Remove particular item from dictionary using pop() method >>> d {1: 'a', 2: 'd', 4: 'r', 6: 'h'} >>> d.pop(2) 'd' >>> d {1: 'a', 4: 'r', 6: 'h’} All the items can be removed at once using the clear() method. use the del keyword to remove individual items or the entire dictionary itself >>>d.clear() ---- all items are removed >>>del d ----entire directory is removed >>> del d ---- deletes particular item Properties of dictionary keys Dictionary values have no restrictions. They can be any object. This is not true for keys. Things to remember about keys— 1)no duplicate key is allowed. This means more than one entry per key not allowed. If done so the last assignment is retained >>> dict={'name':'neeta', 'name':'geeta'} >>> dict {'name': 'geeta’} 2) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys Looping over dictionary If you use a dictionary in a for statement, it traverses the keys of the dictionary. The keys are not in particular order. Use sorted function for the keys in sorted order. >>> d {1: 'z', 4: 'r', 6: 'j', 3: 't', 7: 'e’} >>> for i in d: print(i,d[i]) Output--- 1z 4r 6j 3t 7e >>> for i in sorted(d): print(i, d[i]) Output--- 1z 3t 4r 6j 7e Dictionary comprehension Use to create new dictionary from iterable. It consists of an expression pair (key: value) followed by for statement inside curly braces {}. Example— >>> squares = {x: x*x for x in range(6)} >>> print(squares) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} >>> >>> type(squares) in operator We can test if a key is in a dictionary or not using the keyword in. Membership test is for keys only, not for values. >>> squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} >>> print(1 in squares) True >>> print(2 not in squares) True >>> print(49 in squares) False >>> print(9 in squares) True Built in functions with dictionary Built-in functions like all(), any(), len(), sorted() etc are commonly used with dictionary to perform different tasks. Try yourself… similar to list, tuple Dictionary methods 1) clear()– removes all items from dictionary 2)copy()—returns a shallow copy of the dictionary 3) fromkeys(seq [,v])--- Return a new dictionary with keys from seq and value equal to v (defaults to None) keys = {'a', 'e', 'i', 'o', 'u' } value = 'vowel' vowels = dict.fromkeys(keys, value) print(vowels) Output— {'i': 'vowel', 'a': 'vowel', 'u': 'vowel', 'e': 'vowel', 'o': 'vowel’} 4) get() -- The get() method returns the value for the specified key if key is in dictionary. Syntax---- dict.get(key[, value]) key - key to be searched in the dictionary value (optional) - Value to be returned if the key is not found. The default value is None The get() method returns: the value for the specified key if key is in dictionary. None if the key is not found and value is not specified. value if the key is not found and value is specified. >>> person = {'name': 'yash', 'age': 22} >>> print('Name: ', person.get('name')) Name: yash >>> print('Age: ', person.get('age')) Age: 22 >>> print('Salary: ', person.get('salary')) Salary: None >>> print('Salary: ', person.get('salary', 0.0)) Salary: 0.0 >>> 5) has_key(key)- returns true if a given key is available in the dictionary, otherwise it returns a false 6) items() --returns a list of dict's (key, value) tuple pairs >>> person.items() dict_items([('name', 'yash'), ('age', 22)]) 7) keys()-- returns a list of all the available keys in the dictionary >>> person.keys() dict_keys(['name', 'age’]) 8)values()-- returns a list of all the values available in a given dictionary >>> person.values() dict_values(['yash', 22]) 9) update()-- adds dictionary dict2's key-values pairs in to dict1 dict1.update(dict2) >>> d1={'salary':20000} >>> d1 {'salary': 20000} >>> person.update(d1) >>> person {'name': 'yash', 'age': 22, 'salary': 20000} >>> Example You are given a string and you want to count how many times each letter appears …. Creating Dictionary which maps letter to frequency. def letterfrequency(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 return d s=input("enter a string -") print(" the dictionary that maps letter to frequency ") lfrequency=letterfrequency(s) print(lfrequency) Output— enter a string -good morning the dictionary that maps letter to frequency {'g': 2, 'o': 3, 'd': 1, ' ': 1, 'm': 1, 'r': 1, 'n': 2, 'i': 1} Extend above program ----- Now invert --to create a dictionary that maps from frequencies to letters Output---- enter a string -good morning the dictionary that maps letter to frequency {'g': 2, 'o': 3, 'd': 1, ' ': 1, 'm': 1, 'r': 1, 'n': 2, 'i': 1} dictionary that maps frequency to letter {2: ['g', 'n'], 3: ['o'], 1: ['d', ' ', 'm', 'r', 'i']} >>> [hint--list as values in dictionary] Solution- #dictionary that maps from frequencies to letters. #list as values in dictionary def invert_dict(d): inverse = dict() for key in d: val = d[key] if val not in inverse: inverse[val] = [key] else: inverse[val].append(key) return inverse inverse=invert_dict(lfrequency) print(" dictionary that maps frequency to letter") print(inverse) set A set is an unordered collection of items. Every element is unique (no duplicates) and must be immutable (which cannot be changed). The set itself is mutable. We can add or remove items from it. Sets can be used to perform mathematical set operations like union, intersection, symmetric difference etc. Creating set A set is created by placing all the items (elements) inside curly braces {}, separated by comma or by using the built-in function set(). It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have a mutable element, like list, set or dictionary, as its element. Empty curly braces {} will make an empty dictionary in Python. To make a set without any elements we use the set() function without any argument. A=set() # set of integers my_set = {1, 2, 3,3,4,5,5} print(my_set) # set of mixed datatypes my_set = {1.0, "Hello", (1, 2, 3),1} print(my_set) Accessing elements in set We cannot access individual values in a set. We can only access all the elements together. But we can also get a list of individual elements by looping through the set. d=set([2,3,2,4,5,4,5]) for i in d: print(i) output- 2 3 4 5 Adding element in a set Sets are mutable. But since they are unordered, indexing has no meaning We can add single element using the add() method and multiple elements using the update() method. The update() method can take tuples, lists, strings or other sets as its argument. Removing element from a set A particular item can be removed from set using methods, discard() and remove(). The only difference between the two is that, while using discard() if the item does not exist in the set, it remains unchanged. But remove() will raise an error in such condition. All items can be removed using clear() method. Note - Mutable data types in Python – list, dictionary, set Immutable data types in Python – number, string, tuple Immutable means once the object is created you cannot change the value. Mutable means once the object is created you can change the value. Try this…. n=10 id(n) 2275483255312 n=20 id(n) 2275483255632 This shows that id of object n which is of number type is different for two assignments. So object n=10 and n=20 are not same object. Programming examples- 1) Write a Python program to capitalize the first character of each word in a string where string is entered by user. 2) Reverse a string and save reverse string in a list. 3) Remove the duplicate characters from a string and create a new string without duplicate character. 4) Write a program that takes two lists and returns True if they have at least one common member. 5) Write a Python program to check whether user entered string starts with specified characters. 6) Write a python program to count repeated characters in a string. Sample string: 'thequickbrownfoxjumpsoverthelazydog' Expected output : o4 e3 u2 h2 r2 t2 7) Write a program to add tuple to list and vice-versa 8) Given a list of tuples, remove all the tuples with length k Input : test_list = [(4, 5), (4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)], K = 2 Output : [(4, ), (8, 6, 7), (1, ), (3, 4, 6, 7)] Explanation : (4, 5) of len = 2 is removed. 9) Write a Python program to sum all the items in a dictionary. 10) Write a program to find the intersection of two list Input : lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] Output : [9, 10, 4, 5]

Use Quizgecko on...
Browser
Browser