Dictionary and Set
Dictionary and Set
Study Notes
Dictionary
Data type built in python language which is based on KEY:VALUE pair.
Dictionary are indexed by keys which are indexed by keys, which can be any immutable type
Main operations on dictionaries are storing and retrieving values from dictionaries.
If you store using a key that is already in use, the old value associated with that key is forgotten.
List cannot be used as key in dictionary as lists can be modified using methods like append and
extend
Examples:
Create an Empty dictionary - A pair of {} creates an empty dictionary
>>> Fruits = {}
Create a dictionary
>>> Fruits = {„Apple’:10, ‘Oranges’: 20,’Banana’: 30}
>>> a = set('abracadabra')
>>> a
{'a', 'r', 'b', 'c', 'd'}
Union
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a | b
Difference
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a - b
{'r', 'b', 'd'}
Intersection
>>> a & b
{'a', 'c'}
Remove method
sets = set([10,20,26,41,54])
print(sets.discard(20))
Output: {41,10,26,54}
Dictionary & Set
Len method
Sets = set([10,20,26,41,54])
Print(Sets.len())
Output: 5