Set and Dictionary

What is set and dictionary

Common set methods

Common dictionary methods

What is set and dictionary: set

Set in math is an unordered collection of non-repeating elements.

For example, 

{1,2} is a set, {2,2} is not a set

{1,2} and {2,1} are the same set

The same idea was adopted in Python. Notably, set in Python is mutable and can store elements of different types:

What is set and dictionary: dictionary

As its name suggests, a dictionary is a collection of entries, which consist of key and value:

Note in that the key (on the left) should be of immutable type, the value (on the right) could be of either mutable or immutable type.

Dictionary itself is mutable (you can add/remove/modify an entry)

Common set methods:

Initialization:

Common set methods:

Adding elements:

set.add() and set.update() can be compared with list.append() and list. extend() to help you understand.

Common set methods:

Removing elements:

Common set methods:

Set operations and their Python correspondences

Intersection of A and B

Union of A and B

Difference of A from B

x belongs to A

Common dictionary methods:

Initialization & Access by key

Common dictionary methods:

Adding entries & Removing entries & Modifying entries

Extra, comparison of ways to access elements:

For iterable (like list and tuple):

list[N], N being an integer, surrounded by brackets []

For dictionary:

dict[key], key being of immutable type, e.g. string or floating number, or integer, surrounded by brackets []

For object:

obj.attribute or obj.method(), the exact names depending on the class definition, preceded by dot .

CS1302 Lecture 6 Chapter 11

By Chung Chan

CS1302 Lecture 6 Chapter 11

  • 109