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.")
In [2]:
print(my_dict1['name'])
# Trying to access keys which doesn't exist
print(my_dict.get('age'))
In [3]:
print(my_dict)
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)
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
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)
In [7]:
### Comprehensive Dictionary i.e. creating dictionary items in loop
cubes={}
cubes = {x: x*x*x for x in range(7)}
print(cubes)
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)
In [9]:
print(fruits)
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
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
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
In [13]:
"""myFavCar = {
"brand": "TATA",
"model": "SAFARI",
"color" : "Ivory",
"year": 2020
}"""
Out[13]:
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)