Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
25 views

Py Unit-2.2

Sets in Python can be created using curly braces or the set() function. They are unordered collections of unique elements that support operations like union, intersection, difference and symmetric difference. Frozen sets are immutable sets that don't support operations that modify the set. Dictionary in Python stores elements as key-value pairs and can be created using curly braces or dict(). It supports methods like get(), update(), keys() and values() to access elements.

Uploaded by

sameermahi905
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Py Unit-2.2

Sets in Python can be created using curly braces or the set() function. They are unordered collections of unique elements that support operations like union, intersection, difference and symmetric difference. Frozen sets are immutable sets that don't support operations that modify the set. Dictionary in Python stores elements as key-value pairs and can be created using curly braces or dict(). It supports methods like get(), update(), keys() and values() to access elements.

Uploaded by

sameermahi905
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Sets and dictionary

-ABHILASH CHAKRABORTY
Sets in Python

 A Set is an unordered collection data type that is iterable, mutable and has no duplicate
elements.
 Python’s set class represents the mathematical notion of a set.
 The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set.
Sets in Python

# Python program to demonstrate sets


Output:
# Same as {"a", "b", "c"}
{'c', 'b', 'a'}
myset = set(["a", "b", "c"])
{'d', 'c', 'b', 'a'}
print(myset)

# Adding element to the set


myset.add("d")
print(myset)
Frozen Sets

 Frozen sets in Python are immutable objects that only support methods and operators
that produce a result without affecting the frozen set or sets to which they are applied.
 While elements of a set can be modified at any time, elements of the frozen set remain
the same after creation.
 If no parameters are passed, it returns an empty frozen set.
Frozen Sets

# Same as {"a", "b","c"}


normal_set = set(["a", "b","c"])
Output:
print("Normal Set")
print(normal_set)
Normal Set
# A frozen set
set(['a', 'c', 'b'])
frozen_set = frozenset(["e", "f", "g"])

print("\nFrozen Set") Frozen Set


print(frozen_set) frozenset(['e', 'g', 'f'])

# Uncommenting below line would cause error as


# we are trying to add element to a frozen set
# frozen_set.add("h")
Using update() method

Output:
set1 = set([ 4, 5, (6, 7)])
set1.update([10, 11])
print("\nSet after Addition of elements using
Set after Addition of
Update: ")
elements using Update:
print(set1)
{10, 11, 4, 5, (6, 7)}
Using pop() method

# Deletion of elements in a Set

# Creating a Set Output:


set1 = set([1, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12])
print("Initial Set: ")
print(set1) Initial Set:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

# Removing element from the Set after popping an element:


# Set using the pop() method {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
set1.pop()
print("\n Set after popping an element: ")
print(set1)
Set Methods

Function Description Function Description


add() Adds an element to a set Removes all elements of another
difference_update()
Removes an element from a set. If the set from this set
remove() element is not present in the set, raise a Removes an element from set if it is
KeyError discard() a member. (Do nothing if the
clear() Removes all elements form a set element is not in set)

copy() Returns a shallow copy of a set Returns the intersection of two sets
intersection()
as a new set
Removes and returns an arbitrary set Updates the set with the
pop() intersection_update()
element. Raise KeyError if the set is empty intersection of itself and another

Updates a set with the union of itself and Returns True if two sets have a null
update() isdisjoint()
others intersection

union() Returns the union of sets in a new set

Returns the difference of two or more sets as


difference()
a new set
Set Methods

Function Description
issubset() Returns True if another set contains this set

issuperset() Returns True if this set contains another set

Returns the symmetric difference of two sets


symmetric_difference()
as a new set
symmetric_difference_update( Updates a set with the symmetric difference
) of itself and another
Dictionary

 Dictionary in Python is an unordered collection of data values, used to store data values
like a map, which unlike other Data Types that hold only single value as an element,
Dictionary holds key:value pair.
 Key value is provided in the dictionary to make it more optimized.
Creating a Dictionary

 Dictionary can be created by placing sequence of elements within curly {} braces,


separated by ‘comma’.
 Dictionary holds a pair of values, one being the Key and the other corresponding pair
element being its Key:value
 Dictionary can also be created by the built-in function dict().
 An empty dictionary can be created by just placing to curly braces{}.
Creating a Dictionary

Dict = {1: ‘Call', 2: ‘Me', 3: ‘Joker'} Output:


print("\nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a Dictionary Dictionary with the use of Integer Keys:


# with Mixed keys {1: ‘Call', 2: ‘Me', 3: ‘Joker'}
Dict = {'Name’: ‘Joker', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ") Dictionary with the use of Mixed Keys:
print(Dict) {1: [1, 2, 3, 4], 'Name': ‘Joker'}
Using clear() method

Output:
Dict = {1: ‘apple', 'name’: ‘Amit', 3: ‘Nile'}

# Deleting entire Dictionary


Dict.clear()
Deleting Entire Dictionary:
print("\nDeleting Entire Dictionary: ") {}
print(Dict)
Dictionary Methods

Methods Description Methods Description

They copy() method returns a shallow copy Produces a printable string representation of
copy() str()
of the dictionary. a dictionary.
Adds dictionary dict2’s key-values pairs to
The clear() method removes all items from update()
clear() dict
the dictionary.
Set dict[key]=default if key is not already in
setdefault()
dict
Removes and returns an element from a
pop() keys() Returns list of dictionary dict’s keys
dictionary having the given key.
items() Returns a list of dict’s (key, value) tuple pairs

Removes the arbitrary key-value pair from Returns true if key in dictionary dict, false
popitem() has_key()
the dictionary and returns it as tuple. otherwise
Create a new dictionary with keys from seq
It is a conventional method to access a fromkeys()
get() and values set to value.
value for a key.
type() Returns the type of the passed variable.
dictionary_nam returns a list of all the values available in a
e.values() given dictionary. cmp() Compares elements of both dict.

You might also like