Py Slides 5 Set Dictionary
Py Slides 5 Set Dictionary
1.discard() :
This method takes the item to delete as an argument.
{1, 2, 3, 4, 5, 6, 3.5, 7, 8, 9}
{4, 5}
>>> s1.intersection(s2)
>>> set1,set2,set3={1,2,3},{3,4,5},{5,6,7}
>>> set2.intersection(set1,set3) set()
3. Difference:
>>> s1={1,2,3,4,5}
>>> s2={4,5,6,7,8}
>>> s1^s2
{1, 2, 3, 6, 7, 8}
>>> s2^s1
>>> s1.symmetric_difference(s2)
>>> s2.symmetric_difference(s1)
Membership :
• We can apply the ‘in’ and ‘not in’ python operators on items
for a set. This tells us whether they belong to the set.
>>> 'p' in {'a','p','p','l','e'}
>>> 0 not in {'0','1'} True
• Deleting a set :
• The del keyword will delete the set completely.
>>> myset = {"apple", "banana", "cherry"}
>>> del myset
>>> myset
Traceback (most recent call last): File "", line 1, in
NameError: name ‘myset’ is not defined
Built-in Set Functions
• Consider set a = {6, 1, 3, 2}
Built-in Function Description Example
Returns True if all elements of the set are >>> all(a)
all()
true (or if the set is empty) True
Returns True if any element of the set is >>> any(a)
any() True
true. If the set is empty, returns False.
Returns the length (number of items) of >>> len(a)
len()
the set. 4
>>> max(a)
max() Returns the maximum element in the set.
6
>>> min(a)
min() Returns the minimum element in the set.
1
Returns a new sorted list from the >>> sorted(a)
sorted() elements in the set (does not sort the set [1, 2, 3, 6]
itself).
Returns the sum of all elements in the set. >>> sum(a)
sum()
(Not applicable to strings) 12
Methods of Sets
Method Description Example
>>> set1={1,2,3}
intersection(), does not update the set on >>> set2={3,4,5}
which it is called. For this, we have the >>> set1.intersection_update(set2)
intersection_update() intersection_update() method. >>> set1
{3}
>>> set1={1,2,3}
>>> set2={3,4,5}
this method updates >>> set1.difference_update(set2)
difference_update() the Python set with the difference. >>> set1
{1,2}
>>> set1={1,2,3}
it updates the set on which it is called >>> set2={3,4,5}
>>> set1.symmetric_difference_update(set2)
symmetric_difference_updatwith the symmetric difference. >>> set1
e() {1, 2, 4, 5}
creates a shallow copy of the >>> set4=set1.copy()
>>> set1,set4
copy() Python set. ({1, 2, 4, 5}, {1, 2, 4, 5})
>>> {1,3,2}.isdisjoint({4,5,6})
returns True if two sets have a null
isdisjoint() True
intersection.
returns true if the set in the argument >>> {1,2}.issubset({1,2,3})
issubset() contains this set. True
Like the issubset() method, this one returns >>> {1,3,4}.issuperset({1,2})
issuperset() True if the set contains the set in the
False
argument.
Python - Dictionary
• A dictionary is mutable and is another container type that can store
any number of Python objects, including other container types.
• Dictionaries consist of pairs (called items) of keys and their
corresponding values.
• Python dictionaries are also known as associative arrays or hash tables.
• The general syntax of a dictionary is as follows:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
• You can create dictionary in the following way as well:
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };
• Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly braces.
An empty dictionary without any items is written with just two curly
braces, like this: {}.
dict() Function :
print(cubes[i])
• To print all the items (key-value) in the dictionary : (1, 1)
(2, 8)
for i in cubes.items(): (3, 21)
print(i) (4, 64)
(5, 125)
Updating Dictionary:
• You can update a dictionary by adding a new entry or item (i.e., a
key-value pair), modifying an existing entry, or deleting an existing
entry as shown below:
• Example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print ("dict['Age']: ", dict['Age']);
print ("dict['School']: ", dict['School']);
• >>> str1='hello'
>>> str2="hello"
>>> str3='''hello'''
>>> str4="""hello"""
%c character
>>> percent=55.50
>>> "%5.2f" % percent '55.50'
>>> "%6.2f" % percent
' 55.50’
• The width of a string can also be specified. The default alignment is right. For
left alignment, give a negative sign to width.
>>>'%4s' % 'abc'
' abc'
>>>'%6s' % 'abc' ' abc'
format() method :
• The format() method can handle complex string formatting more efficiently.
• This method of in-built string class provides the ability to do complex variable
substitutions and value formatting.
• The general syntax of the format() method is as follows:
string.format(str1, str2,...)
• The string itself contains placeholders {}, in which the values of variables are
successively inserted.
• >>>name="Bill"
• >>>age=25
• >>>"My name is {} and I am {} years old.".format(name, age)
• You can also specify formatting symbols by using : instead of %. For example,
instead of %s use {:s} and instead of %d use {:d}.
• >>> "My name is {:s} and I am {:d} years old.".format(name, age)
'My name is Bill and I am 25 years old.'
• String alignment is done with <, > and ^ symbols in the place
holder causing left, right and center alignment, respectively.
• Default is left alignment.
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
1 tm_mon 1 to 12
2 tm_mday 1 to 31
3 tm_hour 0 to 23
4 tm_min 0 to 59
6 tm_wday 0 to 6 (0 is Monday)
Returns a multiline string with a calendar for year year formatted into
three columns separated by c spaces. w is the width in characters of
each date; each line has length 21*w+18+2*c. l is the number of
lines for each week.
2 calendar.firstweekday( )
Returns the current setting for the weekday that starts each week. By
default, when calendar is first imported, this is 0, meaning Monday.
3 calendar.isleap(year)