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 behavior 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.

ExampleEdit & Run
d = {}

print(d)
print(type(d))
Output:
{}<class 'dict'>[Finished in 0.011977100977674127s]

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

ExampleEdit & Run
d = dict()

print(d)
Output:
{}[Finished in 0.010490885004401207s]

Initializing Non-empty dictionaries

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:

ExampleEdit & Run
#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))
Output:
{1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}5[Finished in 0.010148457018658519s]

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

ExampleEdit & Run

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))
Output:
{'January': 31, 'February': 28, 'March': 31, 'April': 30}4[Finished in 0.009523442946374416s]

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.

ExampleEdit & Run

A dictionary with repeated keys

D = {1 : 'CSS', 2: 'PHP', 3:'HTMl', 4: 'Python', 4: 'Javascript'}
print(D)
Output:
{1: 'CSS', 2: 'PHP', 3: 'HTMl', 4: 'Javascript'}[Finished in 0.00971047393977642s]

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.

ExampleEdit & Run

Use tuples as dictionary keys 

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

print(months)
Output:
{('February',): 28, ('April', 'June', 'September', 'November'): 30, ('January', 'March', 'May', 'July'): 31}[Finished in 0.010111723095178604s]

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

ExampleEdit & Run
D = {['April', 'June', 'September', 'November']: 30}
Output:
Traceback (most recent call last):  File "<string>", line 1, in <module>TypeError: unhashable type: 'list'[Finished in 0.00989084504544735s]

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:

ExampleEdit & Run
print(isinstance( {}, dict))
print(isinstance( {1: 'one', 2: 'two', 3: 'three'}, dict ))
print(isinstance( {1, 2, 3, 4}, dict ))
Output:
TrueTrueFalse[Finished in 0.009501102147623897s]

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.

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

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

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.

ExampleEdit & Run
D = {28 : ('February', ), 30:('April', 'June', 'September', 'November'), 31:('January', 'March', 'May', 'July', 'August', 'October', 'December')}

D[0] #raises KeyError
Output:
Traceback (most recent call last):  File "<string>", line 3, in <module>KeyError: 0[Finished in 0.010262893978506327s]

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. 

ExampleEdit & Run
D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
print(D.get(1))
print(D.get(2))
print(D.get(3))

D2 = {28 : ('February', ), 30:('April', 'June', 'September', 'November'), 31:('January', 'March', 'May', 'July', 'August', 'October', 'December')}
print(D2.get(31))
print(D2.get(30))
print(D2.get(29, 'No such Key'))
Output:
CSSPHPHTMl('January', 'March', 'May', 'July', 'August', 'October', 'December')('April', 'June', 'September', 'November')No such Key[Finished in 0.010195150971412659s]

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.

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

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

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

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


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

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:

ExampleEdit & Run
D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
print( D.keys() )

D2 = {28 : ('February', ), 30:('April', 'June', 'September', 'November'), 31:('January', 'March', 'May', 'July', 'August', 'October', 'December')}
print( D2.keys() )
Output:
dict_keys([1, 2, 3, 4])dict_keys([28, 30, 31])[Finished in 0.009895785944536328s]

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

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

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

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

ExampleEdit & Run
D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
print( D.values() )

D2 ={28 : ('February', ), 30:('April', 'June', 'September', 'November'), 31:('January', 'March', 'May', 'July', 'August', 'October', 'December')}
print( D2.values() )
Output:
dict_values(['CSS', 'PHP', 'HTMl', 'Javascript'])dict_values([('February',), ('April', 'June', 'September', 'November'), ('January', 'March', 'May', 'July', 'August', 'October', 'December')])[Finished in 0.010912211146205664s]

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

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

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

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.

ExampleEdit & Run
D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
for i in D.items():
    print(i)
Output:
(1, 'CSS')(2, 'PHP')(3, 'HTMl')(4, 'Javascript')[Finished in 0.009263206040486693s]

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
ExampleEdit & Run
D = {}
D[1] = 'Python'
print(D)

D[2] = 'C++'
print(D)
Output:
{1: 'Python'}{1: 'Python', 2: 'C++'}[Finished in 0.009284003870561719s]

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

ExampleEdit & Run
D = {1: 'Python', 2: 'C++'}
D[2] = "Java"
print(D)
Output:
{1: 'Python', 2: 'Java'}[Finished in 0.009246844099834561s]

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. 

ExampleEdit & Run

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)
Output:
{1: 'one', 2: 'two', 3: 'three', 10: 'ten', 20: 'twenty', 30: 'thirty'}[Finished in 0.009115192806348205s]

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:

ExampleEdit & Run

 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)
Output:
{1: 'one', 2: 'two', 3: 'three', 10: 'ten', 20: 'twenty', 30: 'thirty'}[Finished in 0.009456641972064972s]

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>]
ExampleEdit & Run
D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
del D[2]
print(D)
Output:
{1: 'CSS', 3: 'HTMl', 4: 'Javascript'}[Finished in 0.00951253599487245s]

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

ExampleEdit & Run
D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
del D[8]  #KeyError: 8
Output:
Traceback (most recent call last):  File "<string>", line 2, in <module>KeyError: 8[Finished in 0.009190449956804514s]

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

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

print(D.pop(4))
print(D)
Output:
CSS{2: 'PHP', 3: 'HTMl', 4: 'Javascript'}Javascript{2: 'PHP', 3: 'HTMl'}[Finished in 0.010007219854742289s]

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 in case the key does not exist.

ExampleEdit & Run
D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}

D.pop(8, 'No such Key')
D.pop(8)
Output:
Traceback (most recent call last):  File "<string>", line 4, in <module>KeyError: 8[Finished in 0.01198492688126862s]

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.

ExampleEdit & Run
D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
print(D.popitem())
print(D.popitem())
print(D.popitem())
print(D.popitem())
print(D.popitem())
Output:
(4, 'Javascript')(3, 'HTMl')(2, 'PHP')(1, 'CSS')Traceback (most recent call last):  File "<string>", line 6, in <module>KeyError: 'popitem(): dictionary is empty'[Finished in 0.0102891328278929s]

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

D.clear()
ExampleEdit & Run
D = {1:'CSS', 2:'PHP', 3:'HTMl', 4:'Javascript'}
D.clear()
print(D)
Output:
{}[Finished in 0.0099353629630059s]