Python Sets and Dictionaries

Slides:



Advertisements
Similar presentations
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Advertisements

Python Data Structures CMSC 201. Built in Types Today we will be talking about some other built in types in python! Tuples Sets Dictionaries.
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.
Python Dictionary.
Hashes a “hash” is another fundamental data structure, like scalars and arrays. Hashes are sometimes called “associative arrays”. Basically, a hash associates.
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
CS 177 Week 11 Recitation Slides 1 1 Dictionaries, Tuples.
Beyond Lists: Other Data Structures CS303E: Elements of Computers and Programming.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Built-in Data Structures in Python An Introduction.
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.
Python Data Structures CMSC 201. Built in Types Today we will be talking about some other built in types in python! Tuples Sets Dictionaries.
LECTURE 3 Python Basics Part 2. FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for.
CompSci 101 Introduction to Computer Science Feb 24, 2015 Prof. Rodger.
Introduction to Python Aug 22, 2013 Hee-gook Jun.
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.
Python I/O Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Classic file reading 1 infile = open(’filename.txt’, ’r’) for line.
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.
Python Lists and Sequences Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark List properties What are lists? A list is a mutable.
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.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Python Advanced Data Structures Peter Wad Sackett.
CSC 108H: Introduction to Computer Programming Summer 2012 Marek Janicki.
Intro to CS Nov 21, 2016.
COMPSCI 107 Computer Science Fundamentals
10 - Python Dictionary John R. Woodward.
Topic: Iterative Statements – Part 1 -> for loop
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
Algorithmic complexity: Speed of algorithms
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
When to use Tuples instead of Lists
Containers and Lists CIS 40 – Introduction to Programming in Python
Department of Computer Science,
Data types: Complex types (Dictionaries)
Python Useful Functions and Methods
Lecture 10 Data Collections
CMSC201 Computer Science I for Majors Lecture 20 – Dictionaries
Bryan Burlingame Halloween 2018
Python Useful Functions and Methods
Introduction to Dictionaries
Ruth Anderson UW CSE 160 Winter 2017
Datatypes in Python (Part II)
Algorithmic complexity: Speed of algorithms
Python Advanced Data Structures
Lists Part 1 Taken from notes by Dr. Neil Moore
Topics Dictionaries Sets Serializing Objects. Topics Dictionaries Sets Serializing Objects.
CS 1111 Introduction to Programming Fall 2018
Dictionaries Dictionary: object that stores a collection of data
Michael Ernst CSE 140 University of Washington
Python Lists and Sequences
6. Dictionaries and sets Rocky K. C. Chang 18 October 2018
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
Python I/O Peter Wad Sackett.
Algorithmic complexity: Speed of algorithms
Python Comprehension and Generators
15-110: Principles of Computing
Bryan Burlingame Halloween 2018
Ruth Anderson UW CSE 160 Spring 2018
CSE 231 Lab 8.
Winter 2019 CISC101 5/26/2019 CISC101 Reminders
Introduction to Dictionaries
Python Simple file reading
Python Useful Functions and Methods
CMSC201 Computer Science I for Majors Lecture 19 – Dictionaries
Dictionary.
Introduction to PYTHON
Ruth Anderson UW CSE 160 Winter 2016
Presentation transcript:

Python Sets and Dictionaries Peter Wad Sackett

Set properties What is a set? A set is a mutable collection of unique unordered immutable objects. The set can change. The elements of the set can not change, however an element can be removed or inserted. There can only be one. A simple set assignment: fruits = set() fruits = {’apple’, ’pear’, ’orange’, ’lemon’, ’banana’} print (fruits) Sets work like the mathematical concept of sets

Set methods Size of the set – how many elements in the set. len(fruits) Adding one element to a set. fruits.add(’kiwi’) Adding several elements (as list) to a set, performance for long list. fruits.update([’strawberry’, ’elderberry’]) Removing element, KeyError if not present. fruits.remove(’kiwi’) Removing element, no error if not present. fruits.discard(’kiwi’) Making a shallow copy. f = fruits.copy() Clearing a set. Keeps the list identity. fruits.clear()

Set methods - mathematical Set membership, tests. ’banana’ in fruits ’plum’ not in fruits exotic = {’mango’, ’pomelo’} fruits.isdisjoint(exotic) fruits.issubset(exotic) fruits.issuperset(exotic) Creating new sets with math. common = fruits.intersection(exotic) all = fruits.union(exotic) diff = fruits.difference(exotic) eitheror = fruits.symmetric_difference(exotic) Iteration over a set. What did you expect?? for f in fruits: print(f) Disjoint Green is subset Green is superset

Examples How many different fruits can you input? Using a set to keep track. print(”Please, enter as many fruits as you can. One per line”) print(”Input STOP when you are finished.”) fruits = set() fruit = input(”Enter fruit: ”) while fruit != ’STOP’: fruit = fruit.lower() if fruit in fruits: print(”Cheater, you have already mentioned”, fruit) else: fruits.add(fruit) print(”Fantastic, you know”, len(fruits), ”different fruits.”) Looking at the code, the structure is quite similar to reading a file line by line using the readline method.

Examples Imagine that we have somehow created a set with all known fruits. Then the program could be extended like this and we could have competitions in who knows most fruits. print(”Please, enter as many fruits as you can. One per line”) print(”Input STOP when you are finished.”) allFruits = set() # Magically filled set with all fruits fruits = set() fruit = input(”Enter fruit: ”) while fruit != ’STOP’: fruit = fruit.lower() if fruit not in allFruits: print(”This is not a fruit, try again,”) elif fruit in fruits: print(”Cheater, you have already mentioned”, fruit) else: fruits.add(fruit) print(”Fantastic, you know”, len(fruits), ”different fruits.”)

Dictionary properties What is a dictionary – dict ? A dict is a mutable collection of unique unordered immutable keys paired with a mutable object The dict can change The keys of the of the set can not change, however an key/value pair can be removed or inserted There can be only one unique key in the dict A simple dict assignment: person = dict() person = {’name’: ’Hannah’, ’age’: 40, ’height’: 172, ’weight’: 66} print (person) print (person[’name’])

Dictionary methods Size of the dict len(person) Adding one key/value pair to a dict person[’eyecolor’] = ’green’ Removing key/value pair, KeyError if not present – see tips del person[’age’] Returns value, returns None if not present – see tips person.get(’age’) Making a shallow copy p = person.copy() Clearing a dict person.clear()

Dictionary methods - iteration Dict membership, test if ’weight’ in person: # some code if ’gender’ not in person: Iteration with dicts – see tips for k in person.keys(): print(k) for v in person.values(): print(v) for i in person.items(): print(i, i[0], i[1])

Examples Counting occurrences of different chars in a string – not knowing in advance which are present. Could be DNA. unknownStr = ’TCAGAACTGNACTACGCANTACGACTCAG’ counts = dict() for char in unknownStr: if char in counts: counts[char] += 1 else: counts[char] = 1 print(”Occurrences in string”) # We want the output sorted by the char for char in sorted(counts.keys()): print(”{}: {:4d}”.format(char, counts[char]))

Tips and Tricks – iteration Dict methods keys() and values() do not return a list. They return an iterable, meaning you can iterate over them ”like a list”. You can make the iterable into a real list by applying the list() function. Then you can use list methods on the resulting list. Remember, the list is a copy. keysList = list(person.keys()) It will mess up the dict if you iterate over it while removing elements. for k in testDict.keys(): # Do not if testDict[k] < 10: # use this method del testDict[k] # to remove elements Below is the safe way to do it, as your keyList is different (copy) from the Dict_Keys iterable the keys() method returns. keyList = list(testDict.keys()) # Removing for k in keyList: # elements if testDict[k] < 10: # like this del testDict[k] # is safe

Tips and Tricks - sorting Both sets and dicts are unordered collections, but sometimes it can be nice to have a sorted list of the elements. That can be achieved with the sorted() function. For sets this is really easy. setSortedList = sorted(mySet) With dicts it is quite similar to get a sorted list of the keys or values. dictKeysSortedList = sorted(myDict.keys()) dictValuesSortedList = sorted(myDict.values()) But what if a list of the keys must be sorted according to the value. Here is the dict method get() very useful. keysSortedByValue = sorted(myDict.keys(), key=myDict.get) Any function/method can be used as sort key, including those you make yourself, as long as it only takes one parameter. Notice the sorted() function returns a list, i.e. it listifyes the inputted iterable, no matter if it was a set or dict keys or something else.

Tips and Tricks - performance A look-up in a set or a dict is very fast – constant time. This means that if does not matter how big the set/dict is, the look-up takes the same amount of time. This is completely different from lists where the look-up scales with the size of the list. myList = [’A’, ’B’, ’C’] mySet = {’A’, ’B’, ’C’} myDict = {’A’: 5, ’B’: 2, ’C’: 7} if ’A’ in myList: # slow if ’A’ in mySet: # fast if ’A’ in myDict: # fast However, if you know the position of the wanted element in the list, then it is faster to get the value from the list than the dict. val = myList[0] is faster than val = myDict[’A’]