You are on page 1of 6

CREATE A SET IN PYTHON

Use curly braces to create a set. An Example is shown


below

To create an empty set


You cannot create an empty set using only curly braces, as you created an empty
list. You must have to declare an empty set as shown below. cast=set()

Use len(setname) command to check the length of set

Use If command to check for a specific element in set.


Because elements in the sets are not stored in order, use for loop to iterate over
every element in the list.

Like lists you can add more elements in sets.

To remove elements from sets, Use discard method on sets as shown below

Discard method has advantage, if the element that you are trying to discard in the
set is not present in there is nor error raised in python.

But if you try to remove any element, using remove method on the set. Python
raises an error if element is not present in the set.
How to check whether a set is subset of another

Using equal symbol to check whether sets contain subsets or not

Union of sets using Union method

Intersection of sets using intersection command


Difference of two sets using difference command

DICTIONARIES
A dictionary is a container that keeps associations between keys and values. Every key
in the dictionary has an associated value. Keys are unique, but a value may be
associated with several keys. Figure 7 gives a typical example: a dictionary that
associates names with colors might describe the favorite colors of various people. The
dictionary structure is also known as a map because it maps a unique key to a value. It
stores the keys, values, and the associations between them.

HOW TO CREATE A DICTIONARY


Use set structure to create a dictionary. {Key : Value, Key2 : Value2}
How to Access Dictionary Values:
To access dictionary values use print function. In argument give dictionary names along
with key as shown below. Pay special attention to the format of the command

To add new element in dictionary:


Just enter dictionary name and key in following way and place value of key after equal
sign. Suppose you want to modify above given dictionary and want to add favorite color
of imran as blue. Follow the given steps

To remove an element from dictionary use the pop method in the following way
To access whole dictionary, use the loop in the following way

You might also like