Dictionary in Python

DICTIONARY
In [1]:
"""Dictionary is a mutable  collection of pair of keys and their corresponding values. Where keys
are always unique."""
### WORKING WITH DICTIONARIES
my_dictionary1={}
my_dictionary2=dict()
print("my_dictionary1:", type(my_dictionary1))
print("my_dictionary2:",type(my_dictionary2))
#print("cmp:",my_dictionary1.cmp(my_dictionary2)) ### Python 3 do not support cmp( )
print("cmp:", my_dictionary1==my_dictionary2)
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'dataMinining', 2: 'dataScience', 3: 'dataAnalytics'}
print("numerical key dict", my_dict)
# dictionary with mixed keys
my_dict1 = {'name': 'John', 1: [2, 4, 3]}
print("mixed key dict", my_dict1)
# using dict()
my_dict = dict({1:'dataMinining', 2:'dataScience', 3:'dataAnalytics'})
print("item and key dict", my_dict)
# from sequence having each item as a pair
my_dict2 = dict([(1,'dataMinining'), (2,'dataScience')])
print("item-pair together dict", my_dict2)
person = {"name": "Asha", "age": 16}
print(f"{person['name']} has {person['age']} years of teaching experience.")
my_dictionary1: <class 'dict'>
my_dictionary2: <class 'dict'>
cmp: True
numerical key dict {1: 'dataMinining', 2: 'dataScience', 3: 'dataAnalytics'}
mixed key dict {'name': 'John', 1: [2, 4, 3]}
item and key dict {1: 'dataMinining', 2: 'dataScience', 3: 'dataAnalytics'}
item-pair together dict {1: 'dataMinining', 2: 'dataScience'}
Asha has 16 years of teaching experience.
In [2]:
print(my_dict1['name'])
# Trying to access keys which doesn't exist
print(my_dict.get('age'))
John
None
In [3]:
print(my_dict)
{1: 'dataMinining', 2: 'dataScience', 3: 'dataAnalytics'}
In [4]:
### adding new key-value or changing the value of an existing key
my_dict1 = {'name':'John', 'age': 26}
# update value
my_dict1['age'] = 27
#Output: {'age': 27, 'name': 'Jack'}
print(my_dict1)
# add item
my_dict1['address'] = 'Capetown'  
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict1)
{'name': 'John', 'age': 27}
{'name': 'John', 'age': 27, 'address': 'Capetown'}
In [5]:
### create a dictionary
squares = {1:1, 2:4, 3:9, 4:16, 5:25, 6:36}  
# remove a particular item
# Output: 16
print(squares.pop(4))  
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
# remove an arbitrary item
# Output: (1, 1)
print(squares.popitem())
# Output: {2: 4, 3: 9, 5: 25}
print(squares)
# delete a particular item
del squares[3]  
# Output: {2: 4, 3: 9}
print(squares)
# remove all items
squares.clear()
# Output: {}
print(squares)
# delete the dictionary itself
del squares
# print(squares) ### Throws Error as the squares dictionary is deleted
16
{1: 1, 2: 4, 3: 9, 5: 25, 6: 36}
(6, 36)
{1: 1, 2: 4, 3: 9, 5: 25}
{1: 1, 2: 4, 5: 25}
{}
In [6]:
###Dictionary Functions
DataScience = {}.fromkeys(['Math','Stats','Principles of Data Science'], 0)
print(DataScience)
###{'Math': 0, 'Stats': 0, 'Principles of Data Science': 0}
for item in DataScience.items(): ##items() is a function that returns the items of dictionary
    print(item)
list(sorted(DataScience.keys()))
# Output: ['Math','Principles of Data Science', 'Stats']
DataScience['Math'] = "Dr. Biswas"
DataScience['Principles of Data Science'] = "Dr. Rajesh"
print(DataScience)
{'Math': 0, 'Stats': 0, 'Principles of Data Science': 0}
('Math', 0)
('Stats', 0)
('Principles of Data Science', 0)
{'Math': 'Dr. Biswas', 'Stats': 0, 'Principles of Data Science': 'Dr. Rajesh'}
In [7]:
### Comprehensive Dictionary i.e. creating dictionary items in loop
cubes={}
cubes = {x: x*x*x for x in range(7)}
print(cubes)
{0: 0, 1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216}
In [8]:
###SET of Groccery Items
fruits={"Apple","Banana","Cherry","Durian"}
print("fruits belongs to", type(fruits),"& contains", fruits)
print(fruits)
veggies={"Aspargus","Beetroot","Cabbage","Drumstick"}
print("veggies belongs to",type(veggies),"& contains", veggies)
snacks={"Almonds","Biscuits","Chocolates"}
print("snacks belongs to",type(snacks),"& contains", snacks)
####Dictionary
market={1: fruits, 2:veggies, 3:snacks}
print(market)
fruits belongs to <class 'set'> & contains {'Banana', 'Cherry', 'Apple', 'Durian'}
{'Banana', 'Cherry', 'Apple', 'Durian'}
veggies belongs to <class 'set'> & contains {'Drumstick', 'Aspargus', 'Cabbage', 'Beetroot'}
snacks belongs to <class 'set'> & contains {'Biscuits', 'Almonds', 'Chocolates'}
{1: {'Banana', 'Cherry', 'Apple', 'Durian'}, 2: {'Drumstick', 'Aspargus', 'Cabbage', 'Beetroot'}, 3: {'Biscuits', 'Almonds', 'Chocolates'}}
In [9]:
print(fruits)
{'Banana', 'Cherry', 'Apple', 'Durian'}
In [10]:
####Accessing Dictionary content
print(market, "\n") #entire dictionary
print(market.values(), "\n")#Only values
print(market.keys(),"\n") #Only Keys
print(market[2]) # Values w.r.t a specific Key
{1: {'Banana', 'Cherry', 'Apple', 'Durian'}, 2: {'Drumstick', 'Aspargus', 'Cabbage', 'Beetroot'}, 3: {'Biscuits', 'Almonds', 'Chocolates'}} 
dict_values([{'Banana', 'Cherry', 'Apple', 'Durian'}, {'Drumstick', 'Aspargus', 'Cabbage', 'Beetroot'}, {'Biscuits', 'Almonds', 'Chocolates'}]) 
dict_keys([1, 2, 3]) 
{'Drumstick', 'Aspargus', 'Cabbage', 'Beetroot'}
In [11]:
###Removing contents of the dictionary and deleting the dictionary
print(market.clear())    # clears all entries in dictionary
del market
print(market) ###Give error as variable is already deleted
None
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-11-c02f0c979ac4> in <module>
      2 print(market.clear())    # clears all entries in dictionary
      3 del market
----> 4 print(market) ###Give error as variable is already deleted
NameError: name 'market' is not defined
In [12]:
myFavCar = {
  "brand": "TATA",
  "model": "SAFARI",
  "year": 2000
}
print(myFavCar)
myFavCar.update({"year": 2020})
myFavCar.update({"color": "Ivory"}) ##This adds new key-value
print(myFavCar)
# Using del to remove a dict 
# removes color 
print(myFavCar)
del myFavCar["color"] 
#del myFavCar[0] 
"""However if you try to delete an element with a key which doesn't exists it will give you an error. 
Uncomment the above line and observe yourself"""
####delete etire dictionary
del myFavCar
{'brand': 'TATA', 'model': 'SAFARI', 'year': 2000}
{'brand': 'TATA', 'model': 'SAFARI', 'year': 2020, 'color': 'Ivory'}
{'brand': 'TATA', 'model': 'SAFARI', 'year': 2020, 'color': 'Ivory'}
In [13]:
"""myFavCar = {
    "brand": "TATA",
    "model": "SAFARI",
    "color" : "Ivory",
    "year": 2020
}"""
Out[13]:
'myFavCar = {\n    "brand": "TATA",\n    "model": "SAFARI",\n    "color" : "Ivory",\n    "year": 2020\n}'
In [14]:
dictionary_pjc={ 1:'Rachel',2:'Ross',3:'Monica',4: 'Shandler',5: 'Phoebie',6: 'Joe'}
print(type(dictionary_pjc))
print("contents of the dictionary_pjc are : ")
print(dictionary_pjc)
print("\n")
print("The value : ",dictionary_pjc[1])
print("Update the dictionary value : ")
dictionary_pjc['athira']='hardly working'
print(dictionary_pjc)
print("Delete the value of a dictionary ")
del dictionary_pjc['athira']
print(dictionary_pjc)
print("\n")
dictionary_pjc[1]= "US"
print(dictionary_pjc)
dictionary_pjc[1]='MUSKAAN'
print(dictionary_pjc)
#If the key values are simple strings, they can be specified as keyword arguments. So here is yet another way to define MLB_team:
print("Dictionary definition version 3")
MLB_team_3 =dict(
  Colorado='Rockies',
  Boston='Red Sox',
  Minnesota='Twins',
  Milwaukee='Brewers',
  Seattle='Mariners'
)
d = {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
# here the keys are 0,1,2,3
# values are a,b,c,d
print(d[0])
d = {3: 'd', 2: 'c', 1: 'b', 0: 'a'}
print(d[0])
alphabet1={1:'a1',2:'b1', 3:'c1', 4:'d1'}
alphabet2={1:'a2',2:'b2', 3:'c2', 4:'d2'}
print("\n\nDictionary Methods\n\n")
print("Clear the contents of alphabet1")
alphabet1.clear()
print("Contents of alphabet1 are : ",alphabet1)
print("\n\n Using copy( ) method")
alphabet1=alphabet2.copy()
print("Contents of alphabete1 after copy method : ",alphabet1)
print("\n\n d.fromkeys(s, v) Returns a dict whose keys are the items in sequence s and whose values are None or v if v is given \n")
vowels_keys = {'a', 'e', 'i', 'o', 'u' }
values=('vowels')
dictionary_vowels=dict.fromkeys(vowels_keys)
print("\n\n Demonstration of fromkeys method (providing only keys) : \n",dictionary_vowels)
dictionary_vowels=dict.fromkeys(vowels_keys,values)
print("\n\n Demonstration of fromkeys method (providing keys and values): \n",dictionary_vowels)
pjc_keys={
  'Rachel',
  'Ross',
  'Monica',
  'Shandler',
  'Phoebie',
  'Joe',
  'Kaufman'
}
values2=('Warner Brothers','David Crane')
dictionary_pjc_3=dict.fromkeys(pjc_keys,values2)
print(dictionary_pjc_3)
print('\n d.get(k) Returns key k’s associated value, or None if k isn’t in dict d')
print(dictionary_vowels.get('a'))
print('\n d.get(k, v) Returns key k’s associated value, or v if k isn’t in dict d')
v=('NA')
print(dictionary_vowels.get('b',v))
print(dictionary_vowels.get('a',v))
print('\n d.items() Returns a view of all the (key, value) pairs in dict d')
print("\n Demonstration of items method : \n",dictionary_vowels.items())
print('\n d.keys() Returns a view of all the keys in dict d')
print("\n Demonstration of keys() method : \n",dictionary_vowels.keys())
print("\n\n d.values() Returns a view of all the values in dict d\n")
print("\n Demonstration of values() methods : \n",dictionary_vowels.values())
print("\n\n d.pop(k) Returns key k’s associated value and removes the item whose key is k, or raises a KeyError exception if k isn’t in d \n\n")
print(dictionary_vowels.pop('a'))
print(dictionary_vowels)
print("\n\n d.pop(k, v) Returns key k’s associated value and removes the item whose key is k, or returns v if k isn’t in dict d")
print(dictionary_vowels.pop('a',v)) # output will be NA
dictionary_vowels['a']='vowels' # adding a to the dictionary_vowels
print(dictionary_vowels)
print("\n\n d.popitem() Returns and removes an arbitrary (key, value) pair from dict d, or raises a KeyError exception if d is empty")
print(dictionary_vowels.popitem())
print(dictionary_vowels)
print("\n\n d.setdefault(k, v) The same as the dict.get() method, except that if the key is not in dict d, a new item is inserted with the key k, and with a value of None or of v if v is given \n\n")
dictionary_vowels.setdefault('z')
dictionary_vowels.setdefault('b','not a vowels')
print(dictionary_vowels)
alphabet1={1:'a1',2:'b1', 3:'c1', 4:'d1'}
alphabet2={1:'a2',2:'b2', 3:'c2', 4:'d2',5:'e2'}
print("\n\n Adds every (key, value) pair from a that isn’t in dict d to d, and for every key that is in both d and a, replaces the corresponding value in d with the one in a—a can be a dictionary, an iterable of (key, value) pairs, or keyword arguments \n\n")
alphabet1.update(alphabet2)
print("\n\nUpdate alphabet1 is \n",alphabet1)
print("\n\n alphabet2 contents are : \n",alphabet2)
alphabet1={1:'a1',2:'b1', 3:'c1', 4:'d1'}
alphabet1.update(dictionary_vowels)
print("\n\nUpdate alphabet1 is \n",alphabet1)
print("\n\n dictionary_vowels contents are : \n",dictionary_vowels)
<class 'dict'>
contents of the dictionary_pjc are : 
{1: 'Rachel', 2: 'Ross', 3: 'Monica', 4: 'Shandler', 5: 'Phoebie', 6: 'Joe'}
The value :  Rachel
Update the dictionary value : 
{1: 'Rachel', 2: 'Ross', 3: 'Monica', 4: 'Shandler', 5: 'Phoebie', 6: 'Joe', 'athira': 'hardly working'}
Delete the value of a dictionary 
{1: 'Rachel', 2: 'Ross', 3: 'Monica', 4: 'Shandler', 5: 'Phoebie', 6: 'Joe'}
{1: 'US', 2: 'Ross', 3: 'Monica', 4: 'Shandler', 5: 'Phoebie', 6: 'Joe'}
{1: 'MUSKAAN', 2: 'Ross', 3: 'Monica', 4: 'Shandler', 5: 'Phoebie', 6: 'Joe'}
Dictionary definition version 3
a
a
Dictionary Methods
Clear the contents of alphabet1
Contents of alphabet1 are :  {}
 Using copy( ) method
Contents of alphabete1 after copy method :  {1: 'a2', 2: 'b2', 3: 'c2', 4: 'd2'}
 d.fromkeys(s, v) Returns a dict whose keys are the items in sequence s and whose values are None or v if v is given 
 Demonstration of fromkeys method (providing only keys) : 
 {'i': None, 'e': None, 'a': None, 'o': None, 'u': None}
 Demonstration of fromkeys method (providing keys and values): 
 {'i': 'vowels', 'e': 'vowels', 'a': 'vowels', 'o': 'vowels', 'u': 'vowels'}
{'Rachel': ('Warner Brothers', 'David Crane'), 'Monica': ('Warner Brothers', 'David Crane'), 'Ross': ('Warner Brothers', 'David Crane'), 'Joe': ('Warner Brothers', 'David Crane'), 'Kaufman': ('Warner Brothers', 'David Crane'), 'Phoebie': ('Warner Brothers', 'David Crane'), 'Shandler': ('Warner Brothers', 'David Crane')}
 d.get(k) Returns key k’s associated value, or None if k isn’t in dict d
vowels
 d.get(k, v) Returns key k’s associated value, or v if k isn’t in dict d
NA
vowels
 d.items() Returns a view of all the (key, value) pairs in dict d
 Demonstration of items method : 
 dict_items([('i', 'vowels'), ('e', 'vowels'), ('a', 'vowels'), ('o', 'vowels'), ('u', 'vowels')])
 d.keys() Returns a view of all the keys in dict d
 Demonstration of keys() method : 
 dict_keys(['i', 'e', 'a', 'o', 'u'])
 d.values() Returns a view of all the values in dict d
 Demonstration of values() methods : 
 dict_values(['vowels', 'vowels', 'vowels', 'vowels', 'vowels'])
 d.pop(k) Returns key k’s associated value and removes the item whose key is k, or raises a KeyError exception if k isn’t in d 
vowels
{'i': 'vowels', 'e': 'vowels', 'o': 'vowels', 'u': 'vowels'}
 d.pop(k, v) Returns key k’s associated value and removes the item whose key is k, or returns v if k isn’t in dict d
NA
{'i': 'vowels', 'e': 'vowels', 'o': 'vowels', 'u': 'vowels', 'a': 'vowels'}
 d.popitem() Returns and removes an arbitrary (key, value) pair from dict d, or raises a KeyError exception if d is empty
('a', 'vowels')
{'i': 'vowels', 'e': 'vowels', 'o': 'vowels', 'u': 'vowels'}
 d.setdefault(k, v) The same as the dict.get() method, except that if the key is not in dict d, a new item is inserted with the key k, and with a value of None or of v if v is given 
{'i': 'vowels', 'e': 'vowels', 'o': 'vowels', 'u': 'vowels', 'z': None, 'b': 'not a vowels'}
 Adds every (key, value) pair from a that isn’t in dict d to d, and for every key that is in both d and a, replaces the corresponding value in d with the one in a—a can be a dictionary, an iterable of (key, value) pairs, or keyword arguments 
Update alphabet1 is 
 {1: 'a2', 2: 'b2', 3: 'c2', 4: 'd2', 5: 'e2'}
 alphabet2 contents are : 
 {1: 'a2', 2: 'b2', 3: 'c2', 4: 'd2', 5: 'e2'}
Update alphabet1 is 
 {1: 'a1', 2: 'b1', 3: 'c1', 4: 'd1', 'i': 'vowels', 'e': 'vowels', 'o': 'vowels', 'u': 'vowels', 'z': None, 'b': 'not a vowels'}
 dictionary_vowels contents are : 
 {'i': 'vowels', 'e': 'vowels', 'o': 'vowels', 'u': 'vowels', 'z': None, 'b': 'not a vowels'}