Download presentation
Presentation is loading. Please wait.
1
Datatypes in Python (Part II)
By Khodeza Begum
2
Outline Dictionary Nested Dictionary Arrays Matrix List Comprehension
3
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
4
Initialization and access
# empty dictionary my_dict = {} # dictionary with integer keys my_dict = {1: 'John', 2: 'Martin'} print (my_dict[1]) # 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]) # using dict() my_dict = dict(x=5, y=0) print (my_dict['x’]) # from sequence having each item as a pair my_dict = dict([(1,'apple'), (2,'ball')]) print (my_dict.get(1)) print (my_dict.get(3)) (Not a KeyError) Output: 5 Output: John Output: apple Output: None Output: 2
5
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 = " ") # Add my_dict[3] = 'Address' for key,value in my_dict.items(): print (key,value) print(my_dict.pop(3)) # or del my_dict[3] ……….. my_dict.clear() Output: 1 Ashton 2 Martin 3 Address Output: Ashton Martin Output: 1 Ashton 2 Martin
6
Dictionary comprehension and built-in functions
squares = {x: x*x for x in range(4)} print(squares) # Built-in functions print(1 in squares) print(9 in squares) print(len(squares)) print(sorted(squares)) #Slicing l = [0,3] print (dict([(key, squares[key]) for key in l])) Output:{0: 0, 1: 1, 2: 4, 3: 9} Output:{0: 0, 3: 9} Output: True False Output: 4 [0,1,2,3]
7
Other functions copy() fromkeys(seq[, v]) get(key[,d]) keys() values()
popitem() pop(key[,d]) setdefault(key[,d]) update([other]) all() any() cmp()
8
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.
9
Nested Dictionary example
nested_dict = { 'dictA': {'key_1': 'value_1’}, 'dictB': {'key_2': 'value_2’}} example customer = {1: {'User_ID': ' ', 'age': '32', 'gender': 'Female', 'Estimated_salary': '150000', 'Purchased': '1'}, 2: {'User_ID': ' ', 'age': '25', 'gender': 'Male', 'Estimated_salary': '33000', 'Purchased': '0’}} print(customer[1]['Estimated_salary']) print(customer[2]['User_ID']) Output:
10
Nested Dictionary (continued)
#add customer[3] = {'User_ID':' ','age':'470','gender’: 'Male','Estimated_salary':'25000','Purchased' :'1'} #update customer[3]['age'] = '47' print(customer[3]) #del del customer[3] # iterate through each item for p_id, u_info in customer.items(): print("\nPerson ID:", p_id) for key in u_info: print(key + ':', u_info[key]) Output: Person ID: 1 User_ID: age: 32 gender: Female Estimated_salary: Purchased: 1 …………………………………
11
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
12
Array (continued) import array as arr numbers = arr.array('i', [1, 2, 3]) numbers.append(4) print(numbers) numbers.extend([5, 6, 7]) # delete item for the given index del numbers[2] #3rd index print (numbers) # delete item numbers.remove(7) #delete item for the given index print(numbers.pop(3)) print(numbers) Output: array('i', [1, 2, 4, 5, 6, 7]) Output: array('i', [1, 2, 3, 4]) Output: array('i', [1, 2, 4, 5, 6]) Output: array('i', [1, 2, 3, 4,5,6,7]) Output: 5 array('i', [1, 2, 4, 6])
13
Matrix 1 2 3 4 5 6 7 8 9 (Nested list) 4 5 6 3 6 9
print(A[1]) column = [] # empty list for row in A: column.append(row[2]) print(column)
14
NumPy array 1 2 3 4 5 6 7 8 9 4 5 6 3 6 9 9 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][-1])
15
Matrix operations A = np.array([[2, 4], [5, -6]])
B = np.array([[9, -3], [3, 6]]) Addition C = A + B Multiplication M = A.dot(B) Transpose T = np.transpose(A) Slicing S = np.array([[1, 4, 5, 12, 14], [-5, 8, 9, 0, 17], [-6, 7, 11, 19, 21]]) print( S[:2,:4] ) # 2 rows 4 columns 1 4 −
16
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.
17
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*num cubes.append(num) print (cubes) # iterating through using list comprehension num_list = [2, 3, 5] cubes_le = [num*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]
18
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*num cubes.append(num) print (cubes) # iterating through using list comprehension num_list = [2, 3, 5] cubes_le = [num*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]
19
Quiz How can you change num = {'one': 1, 'two': 3} to
num[2] = ‘two’ num[1] = ‘two’ num[‘two’] = 2 num[‘two’] = ‘2’
20
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) {1: 1, 2: 8, 3: 27, 4:64, 5: 125}
21
Quiz What is the output of the following program?
dict = {'c': 97, 'a': 96, 'b': 98} for _ in sorted(dict): print (dict[_]) NameError
22
Quiz What is the output of the following program?
a = {'a':1,'b':2,'c':3} print (a['a','b']) Key Error [1,2] {‘a’:1,’b’:2} (1,2)
23
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)
24
Thank you
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.