In Python, a dictionary represents a collection of unique key-value pairs. Dictionaries are also called Associative arrays or mappings.

A dictionary gets the name from how it associates a particular key to a particular value, just like how an English dictionary associates a word with a definition.

Dictionaries are represented using the builtin dict() class. This class defines the behaviour and methods for working with dictionaries

Unlike in some other data types such as lists where values are accessed with their indices, in dictionaries, values are accessed with their keys

Empty curly braces are used to initialize an empty dictionary.

d = {}

print(d)
print(type(d))

We can also use the builtin dict() function to create an empty dictionary, as in:

d = dict()

print(d)

Initializing Non-empty dictionarries

When initializing non-empty dictionaries, the comma-separated key:value pairs are enclosed in curly braces.

The key part and the value part are separated by a colon, while the items themselves are separated by commas.

Dictioanry syntax in Python

Example of non-empty dictionaries:

#a dictionary to map numbers to their words
d = {1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}

#print the dictionary
print(d)

#print the number of elements in the dictionary
print(len(d))

In the above example, we are associataing a number with its word. 

A dictionary to associate a month with its number of days

months = {'January': 31, 'February':28, 'March': 31, 'April': 30}

print(months)

print(len(months))

All keys in a dictionary must be unique, if a key is repeated, it will get associated with the latest value. Actually, the latest value overwrites the older value.

A dictionary with repeated keys

D = {1 : 'CSS', 2: 'PHP', 3:'HTMl', 4: 'Python', 4: 'Javascript'}
print(D)

In the above example, the key 4 is repeated twice. As shown by the output, only the latest value("Javascript") is retained in the dictionary.

Hashability of dictionary keys

While any object can be used as a value in a dictionary item,  not every object can be used as a dictionary key. For an object to be eligible for use as a key, it must be hashable.

Typically, all immutable values such as integers, floats, strings and tuples are hashable, while mutable objects such as lists , sets and dictionaries are non-hashable. Therefore, we can only use immutable objects as dictionary keys.

Use tuples as dictionary keys 

months = {('February', ): 28, ('April', 'June', 'September', 'November'): 30, ('January', 'March', 'May', 'July'): 31}

print(months)

Trying to use a non-hashable object as a key will raise a TypeError.

D = {['April', 'June', 'September', 'November']: 30}

Check whether an object is a dictionary

Dictionaries in Python are represented using the  built-in dict type.

We can use the isinstance() function with dict as the second parameter to check explicitly whether a given object is a dictionary:

Examples:

isinstance( {}, dict)
//True
isinstance( {1: 'one', 2: 'two', 3: 'three'}, dict )
//True
isinstance( {1, 2, 3, 4}, dict )
//False

Operations on Dictionaries

Dictionaries are unordered, and their keys are unique. This means that some common operations, such as concatenation, repetition, indexing, and slicing, are not applicable to dictionaries. These operations assume an order on the items, which dictionaries do not have.  Additionally, repetition on dictionaries would violate the uniqueness of keys property, which ensures that each key in a dictionary maps to a unique value. 

However, other operations including some which are unique to dictionaries can be performed.  These operations are discussed below.

Accessing the value associated with a key

We use square brackets with key as the parameter, to access an element in the dictionary. The syntax is as follows:

D[key]

The value associated with the given key is returned. 

This is called dictionary lookup because just like looking up a word in a dictionary, you are searching for the corresponding value that is associated with a specific key.

Examples:

D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
D[1]
//'CSS'
D[2]
//'PHP'
D[3]
//'HTML'
D2 ={28 : ('February', ), 30:('April', 'June', 'September', 'November'), 31:('January', 'March', 'May', 'July', 'August', 'October', 'December')}
D2[31]
//('January', 'March', 'May', 'July', 'August', 'October', 'December')
D2[30]
//('April', 'June', 'September', 'November')

Since elements in a dictionary are unordered, we cannot use indexing to access items. If we try accessing elements with their index such as D[index], Python will try associating the given index with a key in the dictionary, if no such key exists, a KeyError will be raised.

D = {28 : (February, ), 30:(April, June, September, November), 31:(January, March, May, July, August, October, December)}
D[0]
//KeyError: 0

The get() method can be used to get the value associated with a given key without raising a KeyError if the given key is not in the dictionary. Additionally, this method takes an optional argument which gets returned as the default value if the given key is not found. Its syntax is as follows:

D.get(k, d)

The value associated with key k will be returned, Otherwise the default value , d,  will be returned. d is optional and if it is not given, it will default to None. 

Examples:

D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
D.get(1)
//'CSS'
D.get(2)
//'PHP'
D.get(3)
//'HTML'
D2 = {28 : ('February', ), 30:('April', 'June', 'September', 'November'), 31:('January', 'March', 'May', 'July', 'August', 'October', 'December')}
D2.get(31)
//('January', 'March', 'May', 'July', 'August', 'October', 'December')
D2.get(30)
//('April', 'June', 'September', 'November')
D2.get(29, 'No such Key')
//'No such Key'

Looping on Dictionaries

Dictionaries are iterable, this means that we can use the for loop to access items in the dictionaries. However, using the for loop with the in operator only returns the keys.

Examples:

D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
for i in D:
   print(i)

//1
//2
//3
//4

D2 = {28 : ('February', ), 30:('April', 'June', 'September', 'November'), 31:('January', 'March', 'May', 'July', 'August', 'October', 'December')}
for i in D2:
    print(i)

//28
//30
//31

We can use dictionary lookup, to access the value associated with the given key during each iteration.

Example:

D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
for i in D:
   print(D[i])

//CSS
//PHP
//HTMl
//Javascript

D2 ={28 : ('February', ), 30:('April', 'June', 'September', 'November'), 31:('January', 'March', 'May', 'July', 'August', 'October', 'December')}
for i in D2:
    print(D2[i])

//('February',)
//('April', 'June', 'September', 'November')
//('January', 'March', 'May', 'July', 'August', 'October', 'December')

The dict class has three important methods which can be used to access keys and values in dictionary instances. 

The keys() method returns an object containing all the keys in the dictionary:

Example:

D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
print( D.keys() )
//dict_keys([1, 2, 3, 4])
D2 = {28 : ('February', ), 30:('April', 'June', 'September', 'November'), 31:('January', 'March', 'May', 'July', 'August', 'October', 'December')}
print( D2.keys() )
//dict_keys([28, 30, 31])

We can use the keys() method to loop through the dictionary keys, as shown below;

D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
for k  in D.keys():
    print(k)

//1
//2
//3
//4

D2 = {28 : ('February', ), 30:('April', 'June', 'September', 'November'), 31:('January', 'March', 'May', 'July', 'August', 'October', 'December')}
for k in D2.keys():
    print(k)

//28
//30
//31

The values() methods,  returns an object containing all the values in a dictionary.

Examples:

D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
print( D.values() )
//dict_values(['CSS', 'PHP', 'HTMl', 'Javascript'])
D2 ={28 : ('February', ), 30:('April', 'June', 'September', 'November'), 31:('January', 'March', 'May', 'July', 'August', 'October', 'December')}
print( D2.values() )
//dict_values([('February',), ('April', 'June', 'September', 'November'), ('January', 'March', 'May', 'July', 'August', 'October', 'December')])
​

We can use this  method to loop through the dictionary values.

Examples:

D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
for v in  D.values():
    print(v)

//CSS
//PHP
//HTMl
//Javascript

D2 = {28 : ('February', ), 30:('April', 'June', 'September', 'November'), 31:('January', 'March', 'May', 'July', 'August', 'October', 'December')}
for v in D2.values():
    print(v)

//('February',)
//('April', 'June', 'September', 'November')
//('January', 'March', 'May', 'July', 'August', 'October', 'December')

The items() method returns an object containing both key value pairs  of each item of the dictionary.  Looping on this object returns a tuple containing the key-value pairs.

Examples:

D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
for i in D.items():
    print(i)

//(1, 'CSS')
//(2, 'PHP')
//(3, 'HTMl')
//(4, 'Javascript')

Adding and Updating Dictionary items

The square brackets can be used to add new items to a dictionary. The syntax is as follows:

D[key] = value

 Example:

D = {}
D[1] = 'Python'
print(D)
//{1: 'Python'}
D[2] = 'C++'
print(D)
//{1: 'Python', 2: 'C++'}

However, if the given key already exists in the dictionary,  the existing value will simply get overwritten with the new value.

D = {1: 'Python', 2: 'C++'}
D[2] = "Java"
print(D)
//{1: 'Python', 2: 'Java'}

Therefore, if the key does not exist in the dictionary, a new item will be added , otherwise, an existing item will get updated.

The update() method

In addition to the d[key] = value syntax, the dict class provides the update() method which can be used to populate a dictionary with multiple elements simultaneously. 

Update a dictionary with elements from another dictionary 

d1 = {1: 'one', 2: 'two', 3: 'three'}

d2 = {10: 'ten', 20: 'twenty', 30: 'thirty'}

#update d1 with elements from d2
d1.update(d2)
print(d1)
//{1: 'one', 2: 'two', 3: 'three', 10: 'ten', 20: 'twenty', 30: 'thirty'}

In the above example we used the update() method to update a dictionary with elements of another dictionary. However, the update() method is more flexible than that. In addition to updating a dictionary with elements from a dictionary-like object, It as well allows an iterable of key-value pairs to be used instead. Consider the following example:

Update a dictionary with a list of two-length tuples

d = {1: 'one', 2: 'two', 3: 'three'}

mylist = [(10, 'ten'), (20, 'twenty'), (30, 'thirty')]

#update d1 with elements from d2
d.update(mylist)
print(d)
//{1: 'one', 2: 'two', 3: 'three', 10: 'ten', 20: 'twenty', 30: 'thirty'}

Deleting dictionary items

The del keyword can be used to effectively delete an item from the dictionary. Its syntax is as follows:

del <dictionary>[<key>]

 Examples:

D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
del D[2]
print(D)
//{1: 'CSS', 3: 'HTMl', 4: 'Javascript'}

The del statement raises a KeyError if the given key does not exist in the dictionary.

Example:

​D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
del D[8]
//KeyError: 8

Similarly, the pop() method can also be used to delete an item. The method returns the value that was associated with the deleted  item.

Examples:

D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
D.pop(1)
//'CSS'
print(D)
//{2: 'PHP', 3: 'HTMl', 4: 'Javascript'}
D.pop(4)
//'Javascript'
print(D)
//{2: 'PHP', 3: 'HTMl'}

The pop() method also raises a KeyError if the key does not exist but we can silence the error by providing an optional argument to the method which will get returned as a default value incase the key does not exist.

D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
D.pop(8)
//KeyError: 8
D.pop(8, 'No such Key')
//'No such Key'

The popitem() method is used to delete a random item in the dictionary. It returns a tuple holding the key and the value of the deleted item. The method takes no arguments. its syntax is as follows:

D.popitem()

This method raises a KeyError if the dictionary is empty.

Example:

D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
D.popitem()
//(2, 'PHP')
D.popitem()
//(3, 'HTML')
D.popitem()
//(1, 'CSS')
D.popitem()
//(4, 'Javascript')
D.popitem()
//KeyError: 'popitem(): dictionary is empty'

 

The clear() method removes all the items in a dictionary, effectively making it an empty dictionary. its syntax is as follows:

D.clear()

Example:

D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
D.clear()
print(D)
//{}