Datatypes in Python (Part II)

Slides:



Advertisements
Similar presentations
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Advertisements

Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Python Data Structures
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
Built-in Data Structures in Python An Introduction.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 Dictionaries and Sets.
Tuples and Dictionaries Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Dictionaries Intro to Computer Science CS 1510 Dr. Sarah Diesburg.
Python Data Structures By Greg Felber. Lists An ordered group of items Does not need to be the same type – Could put numbers, strings or donkeys in the.
Dictionaries. The compound types you have learned about - - strings, lists, and tuples – use integers as indices. If you try to use any other type as.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Python Sets and Dictionaries Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Set properties What is a set? A set is a mutable.
Dictionaries Alexandra Stefan CSE1310 – University of Texas at Arlington.
Python Fundamentals: Complex Data Structures Eric Shook Department of Geography Kent State University.
Section06: Sequences Chapter 4 and 5. General Description "Normal" variables x = 19 – The name "x" is associated with a single value Sequence variables:
String and Lists Dr. José M. Reyes Álamo.
Intro to CS Nov 21, 2016.
Java Arrays and ArrayLists COMP T1 #5
Intro to CS Nov 17, 2016.
10 - Python Dictionary John R. Woodward.
Python Variable Types.
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
CSc 120 Introduction to Computer Programing II
Department of Computer Science,
List comprehensions (and other shortcuts) UW CSE 160 Winter 2016.
Announcements Project 4 due Wed., Nov 7
Section 6: Sequences Chapter 4 and 5.
Lecture 10 Data Collections
CSc 110, Autumn 2017 Lecture 31: Dictionaries
CSc 110, Autumn 2017 Lecture 30: Sets and Dictionaries
LING 388: Computers and Language
Ruth Anderson UW CSE 160 Spring 2018
Intro to Computer Science CS 1510 Dr. Sarah Diesburg
Ruth Anderson UW CSE 160 Winter 2017
Intro to Computer Science CS 1510 Dr. Sarah Diesburg
CHAPTER THREE Sequences.
Guide to Programming with Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
String and Lists Dr. José M. Reyes Álamo.
Presented by Mirza Elahi 10/29/2018
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Topics Sequences Introduction to Lists List Slicing
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
Dictionaries Dictionary: object that stores a collection of data
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Michael Ernst CSE 140 University of Washington
Michael Ernst CSE 140 University of Washington
6. Dictionaries and sets Rocky K. C. Chang 18 October 2018
15-110: Principles of Computing
Topics Sequences Lists Copying Lists Processing Lists
By- Anshul Kumar Class: XI “B”
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
Python Sets and Dictionaries
15-110: Principles of Computing
Topics Sequences Introduction to Lists List Slicing
Winter 2019 CISC101 5/26/2019 CISC101 Reminders
CSE 231 Lab 9.
Introduction to Dictionaries
Sample lecture slides.
Dictionary.
Presentation transcript:

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 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

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

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]

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 example nested_dict = { 'dictA': {'key_1': 'value_1’}, 'dictB': {'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 customer[3] = {'User_ID':'15733883','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: 15694829 age: 32 gender: Female Estimated_salary: 150000 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 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])

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)

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])

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 −5 8 5 12 9 0

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*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]

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]

Quiz How can you change num = {'one': 1, 'two': 3} to 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[_]) 96 98 97 96 97 98 98 97 96 NameError

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)

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