Dictionaries
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 dictionary
myDict = {}
print (myDict)
# dictionary with integer keys
myDict = {1: 'apple', 2: 'ball'}
print( myDict)
# dictionary with mixed keys
myDict = {'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 pair
myDict = dict([(1,'apple'), (2,'ball')])
print (myDict)Accessing Elements
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 returnsNoneinstead ofKeyError, if the key is not found.
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.
Delete Elements
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.
Traversing a Dictionary
Let us visit each element of the dictionary to display its values on screen. This can be done by using a for loop.
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.
Other Dictionary Methods
len(s)
This method returns number of key-value pairs in the given dictionary.
dict.clear()
It removes all items from the particular dictionary.
dict.get(key[, value])
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.
dict.has_key(key)
This function returns ‘True’, if dictionary has a key, otherwise it returns ‘False’.
dict.items()
Return a copy of the dictionary’s list of (key, value) pairs.
dict.keys()
Return a copy of the dictionary’s list of keys.
dict.values()
Return a copy of the dictionary’s list of values.
Last updated
Was this helpful?