L3-1 What is a Dictionary/Hash Table?

In Python it's called Dictionary, in other programming languages people call it Hash Table or Hash Map. These terms are often used interchangeably.

Dictionary is a data structure in Python that stores an unordered collection of

key:value
pairs. Each key must be unique and an immutable type (i.e. string and integers), but the values can be repeated and can be of any type.

Dictionaries are optimized to retrieve values when the key is known.

Creating a Dictionary

Accessing Elements from Dictionary

We use

keys
to access values in dictionary as opposed to using indices. Keys can be used either inside square brackets
[]
or with the
get()
method. Both ways are equivalent.

If we use the square brackets

[]
, Python throws an error in case a key is not found in the dictionary. On the other hand, the
get()
method returns
None
if the key is not found.

Adding/Changing Dictionary Elements

Similar to

lists
, we can add new items or change the value of exisiting items using the assignment operator.

If the key is already present in the dictionary, then the exisiting value gets updated. If the key is not present, then a new

key:value
pair is added to the dictionary

Removing Elements from Dictionary

We can remove a particular item in a dictionary using the

pop(<key>)
method. Note that this method removes an item with the provided
key
and returns the
value
.

We can also remove all the items at once using the

clear()
method.