Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys
It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).
Creating a dictionary
Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
# empty dictionarymyDict ={}print (myDict)# dictionary with integer keysmyDict ={1:'apple',2:'ball'}print( myDict)# dictionary with mixed keysmyDict ={'name':'John',1: [2,4,3]}print (myDict)# using dict()myDict =dict({1:'apple', 2:'ball'})print (myDict)# from sequence having each item as a pairmyDict =dict([(1,'apple'), (2,'ball')])print (myDict)
While indexing is used with other container types to access values, dictionary uses keys. Key can be used either inside square brackets or with the get() method.
The difference while using get() is that it returns None instead of KeyError, if the key is not found.
myDict ={'name':'Jack','age':26}# Output: Jackprint (myDict['name'])# Output: 26print (myDict.get('age'))# Trying to access keys which doesn't exist returns Noneprint (myDict.get('address'))# Trying to access keys which doesn't exist throws KeyError# print myDict['address']
Jack
26
None
Change or Add Elements
Dictionaries are mutable. We can add new items or change the value of existing items using assignment operator.
If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.
We can remove a particular item in a dictionary by using the method pop(). This method removes as item with the provided key and returns the value.
The method, popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary. All the items can be removed at once using the clear() method.
We can also use the del keyword to remove individual items or the entire dictionary itself.
# create a dictionarysquares ={1:1,2:4,3:9,4:16,5:25}# remove a particular itemprint (squares.pop(4))print (squares)# remove an arbitrary itemprint (squares.popitem())print (squares)# delete a particular itemdel squares[5]print (squares)# remove all itemssquares.clear()print (squares)# delete the dictionary itselfdel squares# Throws Error# print squares
Let us visit each element of the dictionary to display its values on screen. This can be done by using a for loop.
ageDict ={'Tim':18,'Charlie':12,'Tiffany':22,'Robert':25}for i in ageDict:print i,':', ageDict[i]
Tim : 18
Tiffany : 22
Robert : 25
Charlie : 12
Merging Dictionaries
Two dictionaries can be merged in to one by using update() method. It merges the keys and values of one dictionary into another and overwrites values of the same key.
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
person ={'name':'Phill','age':22}print ('Name:', person.get('name'))print ('Age:', person.get('age'))# value is not providedprint ('Salary:', person.get('salary'))# value is providedprint ('Salary:', person.get('salary', 0.0))
Name: Phill
Age: 22
Salary: None
Salary: 0.0
dict.has_key(key)
This function returns ‘True’, if dictionary has a key, otherwise it returns ‘False’.