Datatypes in Python Part II By Khodeza Begum
Datatypes in Python (Part II) By Khodeza Begum
Outline • Dictionary • Nested Dictionary • Arrays • Matrix • List Comprehension
Dictionary • Unordered collection of items • Optimized to retrieve value when key is known • {Key: value} pair • Type of keys • Must be unique • String, number or tuple (with immutable elements) • Type of values • Any data type and can repeat
Initialization and access # empty dictionary # using dict() my_dict = {} my_dict = dict(x=5, y=0) # dictionary with integer keys print (my_dict['x’]) my_dict = {1: 'John', 2: 'Martin'} print (my_dict[1]) Output: John # dictionary with mixed keys (first->key type string, second->value type list ) my_dict = {'name': 'John', 1: [2, 4, 3]} print (my_dict[1][0]) Output: 2 Output: 5 # from sequence having each item as a pair my_dict = dict([(1, 'apple'), (2, 'ball')]) print (my_dict. get(1)) Output: apple print (my_dict. get(3)) Output: None (Not a Key. Error)
Change, Add, Delete & Remove # Update my_dict = {1: 'John', 2: 'Martin'} my_dict[1] = 'Ashton' for i in my_dict: print (my_dict[i], end = " ") Output: Ashton Martin for key, value in my_dict. items(): print (key, value) Output: 1 Ashton 2 Martin 3 Address • print(my_dict. pop(3)) # or • del my_dict[3] # Add ………. . my_dict[3] = 'Address' Output: 1 Ashton 2 Martin • my_dict. clear()
Dictionary comprehension and built-in functions # Comprehension #Slicing squares = {x: x*x for x in range(4)} print(squares) l = [0, 3] print (dict([(key, squares[key]) for key in l])) Output: {0: 0, 1: 1, 2: 4, 3: 9} # Built-in functions print(1 in squares) print(9 in squares) Output: True False Output: 4 print(len(squares)) [0, 1, 2, 3] print(sorted(squares)) Output: {0: 0, 3: 9}
Other functions • • • copy() fromkeys(seq[, v]) get(key[, d]) keys() values() popitem() pop(key[, d]) setdefault(key[, d]) update([other]) all() any() cmp()
Nested Dictionary • An unordered collection of dictionary • Slicing Nested Dictionary is not possible. • We can shrink or grow nested dictionary as need. • Like Dictionary, it also has key and value.
Nested Dictionary • nested_dict = { 'dict. A': {'key_1': 'value_1’}, 'dict. B': {'key_2': 'value_2’}} • example • customer = {1: {'User_ID': '15694829', 'age': '32', 'gender': 'Female', 'Estimated_salary': '150000', 'Purchased': '1'}, 2: {'User_ID': '15600575', 'age': '25', 'gender': 'Male', 'Estimated_salary': '33000', 'Purchased': '0’}} print(customer[1]['Estimated_salary']) print(customer[2]['User_ID']) Output: 150000 15600575
Nested Dictionary (continued) #add # iterate through each item for p_id, u_info in customer. items(): customer[3] = {'User_ID': '15733883', 'age': '470', 'gender’: print("n. Person ID: ", p_id) 'Male', 'Estimated_salary': '25000', 'Purchased' for key in u_info: : '1'} print(key + ': ', u_info[key]) #update Output: Person ID: 1 customer[3]['age'] = '47' User_ID: 15694829 print(customer[3]) age: 32 gender: Female #del Estimated_salary: 150000 del customer[3] Purchased: 1 …………………
Array • Collection of elements of the same type • More popular in Java, C/C++, Javascript • Lists are better choice than arrays in Python • array module • Only advised to use array when needed to be interfaced with a C code
Array (continued) import array as arr # delete item for the given index numbers = array('i', [1, 2, 3]) del numbers[2] numbers. append(4) print (numbers) print(numbers) Output: array('i', [1, 2, 3, 4]) numbers. extend([5, 6, 7]) print(numbers) Output: array('i', [1, 2, 3, 4, 5, 6, 7]) #3 rd index Output: array('i', [1, 2, 4, 5, 6, 7]) # delete item numbers. remove(7) print (numbers) Output: array('i', [1, 2, 4, 5, 6]) #delete item for the given index print(numbers. pop(3)) Output: 5 array('i', [1, 2, 4, 6]) print(numbers)
Matrix • A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(A[1]) column = [] # empty list for row in A: column. append(row[2]) print(column)
Num. Py array • import numpy as np B = np. array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(B[1]) print(B[: , -1]) print(B[-1])
Matrix operations •
List Comprehension • An elegant way to define and create lists based on existing lists • Generally more compact and faster than normal functions and loops for creating list • However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly. • Every list comprehension can be rewritten in for loop, but every for loop can’t be rewritten in the form of list comprehension.
List Comprehension • Syntax : [expression for item in existing_list] # iterating through using for loop cubes = [] num_list = [2, 3, 5] for num in numbers: num=num*num cubes. append(num) print (cubes) # iterating through using list comprehension num_list = [2, 3, 5] cubes_le = [num*num for num in num_list] print (cubes_le) # iterating through using list comprehension via lambda cubes_lambda = list(map(lambda x: x*x*x, num_list)) print (cubes_lambda) Output: [8, 27, 125]
List Comprehension • Syntax : [expression for item in existing_list] # iterating through using for loop cubes = [] num_list = [2, 3, 5] for num in numbers: if num%2 != 0: num=num*num cubes. append(num) print (cubes) # iterating through using list comprehension num_list = [2, 3, 5] cubes_le = [num*num for num in num_list if num%2 != 0] print (cubes_le) # iterating through using list comprehension via lambda num_new_list=[num for num in num_list if num %2 != 0] cubes_lambda = list(map(lambda x: x*x*x, num_new_list)) print (cubes_lambda) Output: [27, 125]
Quiz • How can you change num = {'one': 1, 'two': 3} to num = {'one': 1, 'two': 2} a) b) c) d) num[2] = ‘two’ num[1] = ‘two’ num[‘two’] = 2 num[‘two’] = ‘ 2’
Quiz • What is the output of the following program? cubes = {1: 1, 2: 8, 3: 27, 4: 64, 5: 125} print(cubes. pop(4)) print(cubes) a) 64 {1: 1, 2: 8, 3: 27, 5: 125} b) 64 {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
Quiz • What is the output of the following program? dict = {'c': 97, 'a': 96, 'b': 98} for _ in sorted(dict): print (dict[_]) a) b) c) d) 96 98 97 96 97 98 98 97 96 Name. Error
Quiz • What is the output of the following program? a = {'a': 1, 'b': 2, 'c': 3} print (a['a', 'b']) a) b) c) d) Key Error [1, 2] {‘a’: 1, ’b’: 2} (1, 2)
Extra practice transposed = [] matrix = [[1, 2, 3, 4], [4, 5, 6, 8]] for i in range(len(matrix[0])): transposed_row = [] for row in matrix: transposed_row. append(row[i]) transposed. append(transposed_row) print(transposed)
Thank you
- Slides: 24