Dictionary in Python | Create, Example

In the previous tutorials so far, we learned sequence data types in Python such as lists, tuples, and sets. Herein, this tutorial, we will understand Python dictionary.

Dictionary is another built-in data type in Python that is an ordered collection of elements (starting from Python 3.7). It is one of the most versatile data structures for storing data in Python.

Dictionary stores the data element in the form of key-value pairs where keys are unique identifiers associated with each value. Let’s understand it with the help of an example.

Suppose we want to store information about countries and their associated capitals. To store this information, we can build a dictionary with country names as keys and capitals as values, as shown in the below tables.

KeysValues
IndiaNew Delhi
USAWashington, D.C.
EnglandLondon

From the table, it is clear that each country (key) is associated with only one capital (value). For example, “India” key is associated with the value “New Delhi”. Similarly, “USA” key is associated with the value “Washington, D.C.”, and so on. Thus, the key/value pair for this dictionary is the country/capital.

A dictionary is an associative data structure in Python, meaning that data elements are stored in a non-linear style. In the associative data structure, elements are not stored in the sequence entered by the user.

Each element represents a key-value pair. Each key-value pair maps the key to its corresponding value. Thus, the dictionary data structure represents a collection of elements arranged in the form of key-value pairs.

We can access the values of a dictionary by keys easily. So, we do not need to worry about the order in which elements are stored.

On the other hand, list or tuple is a linear data structure in Python in which elements are stored one after another, i.e., the first element, then the second element, then third, and so on. In a linear data structure, we access elements in a sequential order or one after another, or simply access elements directly by indexes.

How to Create a Dictionary in Python?


Creating dictionaries in Python is very simple. The general syntax to create a dictionary is as follows:

dictionary_name = {key1: value, key2: value2, key3: value3, . . . . , keyn: value3}

In the above syntax, each element in the dictionary consists of a key-value pairs which are separated by a colon and enclosed within curly braces {}.

In simple words, every data element in a dictionary is associated with a key value. That is, each key maps a value. The association of a key and its value is called key-value pairs. We can access or retrieve it through its key value.

Let’s take an example to understand it. Consider an example of a telephone directory.

phone_book = {"John" : "0326-345332", "Mark" : "9123-56473", "Deep" : "6543-63745" }

In this example, we have created a dictionary and assigned it to a variable named phone_book. This dictionary has three elements:

  • The primary element is “John” : “0326-345332”. Here, the key is “John” and value is “0326-345332”.
  • The second element is “Mark” : “9123-56473”. Here, the key is “Mark” and the associated value is “9123-56473”.
  • The third element is “Deep” : “6543-63754”. Here, the key is “Deep” and the associated value is “6543-63754”.

From the above example, it is clear that keys, and the corresponding values are strings. However, values in the elements can be of any data type, but keys must be immutable objects.

In fact, keys can only be strings, integers, floating-point values, or tuples. Remember that keys cannot be lists or any other type of mutable object.

Valid Examples of creating Dictionaries in Python

Example1: Creating an empty dictionary.

my_dict = {} # Create an empty dictionary.
print(my_dict)
Output:
       {}

Example 2: Creating a dictionary with integer keys.

# A dictionary having integer keys and string values.
my_dict = {1 : "One", 2 : "Two", 3 : "Three"}
print(my_dict)
Output:
       {1: 'One', 2: 'Two', 3: 'Three'}

In this example, we have created a dictionary of three elements in which keys are integers and values are strings.


Example 3: Creating a dictionary with string keys.

# A dictionary having string keys and string values.
my_dict = {"1" : "One", "2" : "Two", "3" : "Three"}
print(my_dict)
Output:
      {'1': 'One', '2': 'Two', '3': 'Three'}

Example 4: Creating a dictionary with tuple keys.

# A dictionary having tuple keys and list values.
my_dict = {(1, 2) : ["One", "Two"], (3, 4) : ["Three", "Four"], (5, 6) : ["Five", "Six"]}
print(my_dict)
Output:
      {(1, 2): ['One', 'Two'], (3, 4): ['Three', 'Four'], (5, 6): ['Five', 'Six']}

In this example, we have created a dictionary of three elements in which keys are tuples and values are lists.

Example 5: Creating a dictionary with float keys.

# A dictionary having float keys and list values.
my_dict = {1.1 : "Mango", 1.2 : "Orange", 1.3 : "Guava"}
print(my_dict)
Output:
      {1.1: 'Mango', 1.2: 'Orange', 1.3: 'Guava'}

Example 6: Creating a dictionary with mixed types of keys.

# A dictionary having mixed types of keys.
my_dict = {1 : "Integer", 1.2 : "floating-point", "Python" : "String", (1, 2) : "Tuple"}
print(my_dict)
Output:
       {1: 'Integer', 1.2: 'floating-point', 'Python': 'String', (1, 2): 'Tuple'}

In this example, we have created a dictionary of three elements in which keys are of mixed data types, such as integer, floating-point, string, and tuple. However, values are string.

Example 7: Creating a dictionary in which keys and associates values are assigned as pairs.

# A dictionary with sequence having each as a pair.
my_dict = ([(1, "One"), (2, "Two"), (3, "Three")])
print(my_dict)
Output:
      [(1, 'One'), (2, 'Two'), (3, 'Three')]

Example 8: Creating a dictionary with lists as keys.

my_dict = {[1, 2] : "List"}
print(my_dict)
Output:
       TypeError: unhashable type: 'list'

Alternative way to create Dictionaries in Python


There is also a simple alternative way to create a Python dictionary. Python provides a built-in method named dict() which encloses keys and their associated values. The basic syntax to create a dictionary using dict() method is as:

my_dict = dict() # Dictionary with empty keys and values.
print(my_dict)
Output:
      {}


Example 9: Creating a dictionary using dict() method.

my_dict = dict({1: "Mango", 2: "Orange", 3: "Banana", 4: "Apple"})
print(my_dict)
Output:
      {1: 'Mango', 2: 'Orange', 3: 'Banana', 4: 'Apple'}

How to Access Elements on a Dictionary?


In the previous section, we have learned how to create a dictionary with various examples. We have also accessed and printed the complete dictionary by passing the dictionary name to the built-in function print().

Now we will learn how to access individual element on a dictionary based on their key values. We can access elements of a dictionary by placing a key name inside the square bracket [ ]. The general syntax to access individual element of a dictionary in Python is as:

my_dict[key_name]

Here, my_dict is the name of a dictionary and key_name is the name of a key whose value has to be accessed.

Example 10:

# Python program to access data of a dictionary.
my_dict = dict({1: "Mango", 2: "Orange", 3: "Banana", 4: "Apple"})
# Accessing a complete dictionary.
print("Complete dictionary: ", my_dict)

# Accessing the first element of a dictionary.
print("First element: ", my_dict[1])

# Accessing the second element of a dictionary.
print("Second element: ", my_dict[2])

# Accessing the third element of a dictionary.
print("Third element: ", my_dict[3])

# Accessing the fourth element of a dictionary.
print("Fourth element: ", my_dict[4])
Output:
      Complete dictionary:  {1: 'Mango', 2: 'Orange', 3: 'Banana', 4: 'Apple'}
      First element:  Mango
      Second element:  Orange
      Third element:  Banana
      Fourth element:  Apple

In this example, we have created a dictionary of four elements in which keys are integers and their associated values are strings. Then, we have accessed data values by referring to their key names inside square brackets.

Note that if the specified key is not available in the dictionary object, Python will raise KeyError. We can prevent it by using the operator “in” as in the below code:

Example 11:

emp_dict = {1: "John", 2: "Mark", 3: "Mahika"}
if 4 in emp_dict:
    print("Present")
else:
    print("The key is not present.")
Output:
       The key is not present.

Alternative Way to Access Elements on a Dictionary

Alternative way to access an element of a dictionary is by using built-in get() method provided by Python. This method returns None instead of KeyError if the key is not present, as shown in the below example code:

Example 12:

# Python program to access data of a dictionary using get() method.
emp_dict = {1: "John", 2: "Mark", 3: "Mahika"}

# Accessing data value using get() method.
print(emp_dict.get(1))
print(emp_dict.get(2))
print(emp_dict.get(3))
print(emp_dict.get(4))
Output:
      John
      Mark
      Mahika
      None

Python 2 has provided a function named has_key() which will check that the key is present or not. But, it is not available in Python 3 version.

Example 13:

# Python program to access data of a dictionary using get() method.
baby_dict = {"Name": "Mahika", "Birth": [11, "May", 2023], "Time": "1:27 pm", "Day": "Thursday"}

# Accessing data.
print("Name: ", baby_dict.get("Name"))
print("Birth: ", baby_dict.get("Birth"))
print("Time: ", baby_dict.get("Time"))
print("Day: ", baby_dict.get("Day"))
Output:
      Name:  Mahika
      Birth:  [11, 'May', 2023]
      Time:  1:27 pm
      Day:  Thursday

Note that you cannot access or modify a dictionary using the index. You can access and modify values with only keys.

Features of Dictionaries in Python


There are the following key features or characteristics of dictionaries in Python. They are as:

Python dictionary features

(1) Underlying data structure: The underlying data structure of implementing a dictionary in Python is an associative array or hash table. A hash table is a data structure that stores keys with its associated values.

(2) Ordered: From the Python 3.7 version, a dictionary is an ordered collection of elements or objects. It maintains the insertion order of elements entered by the user. For example:

my_dict = {2: "Two", 1: "One", 3: "Three"}
print(my_dict)
Output:
      {2: 'Two', 1: 'One', 3: 'Three'}

(3) Unique keys: A dictionary can contain any number of elements or items. The keys in the dictionary must be unique. They do not allow duplicate keys. In other words, a dictionary can’t contain multiple elements with the same key. If we try to add duplicate keys in the dictionary, the newly added key replaces the old key along with its value. For example:

# A dictionary having duplicate keys.
my_dict = {1: "Two", 1: "One", 1: "Three"}
print(my_dict)
Output:
       {1: 'Three'}

(4) Duplicate values: Values of dictionary keys can have the duplicate values for different elements. They do not have to be unique. For example:

# A dictionary having duplicate values.
my_dict = {1: "AA", 2: "AA", 3: "AA"}
print(my_dict)
Output:
       {1: 'AA', 2: 'AA', 3: 'AA'}

(5) Mutable nature: Python dictionaries are mutable data types, meaning that we can modify or update the values associated with keys after the dictionary’s creation. That is, we can make changes in the existing dictionary object.

We do not need to create a new dictionary object every time. However, keys in the dictionaries are immutable in nature and values are mutable in nature.

(6) Heterogeneous: The biggest advantage of using a dictionary is that we can create a dictionary object of heterogeneous elements. We can store elements of different data types in a single dictionary. Elements having different data types take memory space according to the type of value stored on the list.

(7) Dynamic: Dictionaries are dynamic in nature, meaning that we do not need to declare the size of a dictionary before using it. The dictionaries take memory space according to requirement. The dictionary automatically expands or grows when we add data at the runtime. And, it shrinks automatically when we delete data at the runtime.

(8) Flexibility: The dictionary provides flexibility or scalability to us to store elements. We can easily add or remove elements of a dictionary at run time. A dictionary shrinks or grows in memory according to the requirement.

Moreover, we do not need to define the size of a dictionary at the time of creation. It automatically declares when we assign values in the curly braces.

(9) Functionality: Python dictionary comes with several functions that allow us to easily perform various operations instead of writing long code from scratch. We can use dir(dict) to get a list of all functions provided by a dictionary.

print(dir(dict))
List of functions:
       ['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__',
       '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
       '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', 
       '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', 
       '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', 
       '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', 
       '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 
       'popitem', 'setdefault', 'update', 'values']

(10) Easy to add values: It is very easy to add values in the dictionary. Python offers various methods to add values in the dictionary. We can directly take the input from the user as key-value pairs. We can also take input first in the form of tuple and then assign a tuple as a key to the dictionary and assign lists as values in the dictionary.

(11) Easy to display values: We can easily display different values of the dictionary without iterating over it. To display elements of a dictionary in a simple style, we just need to write the print statement and pass the dictionary object to pass() function which we want to print.

(12) Easy to use: It is very easy to use dictionary data type as compared to other data types. It has the capability to take memory dynamically as well as also provides different methods to provide an easy way for writing code.

(13) Availability of different methods: We can also use a different set of inbuilt methods with a dictionary. We can easily perform various operations by merely calling these methods with the dictionary object.

For instance, to sort elements of a dictionary, we just need to call sort method with dictionary object we want to sort. We do not require writing the complete code for sorting.

Adding and Modifying Entries to Python Dictionary


As usually we know dictionaries are mutable objects in Python, so we can easily add new elements or update the value of existing keys through the assignment operator =.

When we store a key-value pair to a dictionary, Python first checks whether the key already exists on the dictionary or not. If the similar key exists, the value simply gets updated. If it is a unique key, then the Python adds a new key with the value to the dictionary.

The general syntax for adding a new entry to a dictionary is:

dict_name[key] = Value

With this syntax, we can add one value at a time in the dictionary.

Example 15:

# Python program to add entries in a dictionary.
# Creating an empty dictionary.
my_dict = {}
print("Empty dictionary: ", my_dict)

# Adding elements one at a time.
my_dict[0] = "Engineering"
my_dict[1] = "Medical"
my_dict[2] = "MBA"
my_dict[3] = "MCA"
print("\nDictionary after adding four elements: ")
print(my_dict)

# Adding a set of values to a single key.
my_dict[4] = "Science", "Arts", "Commerce"
print("\nDictionary after adding four elements: ")
print(my_dict)
Output:
      Empty dictionary:  {}

      Dictionary after adding four elements: 
      {0: 'Engineering', 1: 'Medical', 2: 'MBA', 3: 'MCA'}

      Dictionary after adding four elements: 
      {0: 'Engineering', 1: 'Medical', 2: 'MBA', 3: 'MCA', 4: ('Science', 'Arts', 'Commerce')}

To modify or update a value stored in a dictionary key, we can assign a new value to the key using the assignment operator =.

Example 16:

# Python program to update values in a dictionary.
my_dict = {1: "Science", 2: "Commerce", 3: "Arts"}
print("Original dictionary: ", my_dict)

# Updating the value of a key.
my_dict[3] = "Diploma"
print("\nDictionary after updating the value of a key: ")
print(my_dict)

# Updating a list of value of a key.
my_dict[3] = ["BCA", "MCA"]
print("\nDictionary after updating a list of values: ")
print(my_dict)
Output:
      Original dictionary:  {1: 'Science', 2: 'Commerce', 3: 'Arts'}

      Dictionary after updating the value of a key: 
      {1: 'Science', 2: 'Commerce', 3: 'Diploma'}

      Dictionary after updating a list of values: 
      {1: 'Science', 2: 'Commerce', 3: ['BCA', 'MCA']}

We can also add a nested key-value pair to a Python dictionary.

Example 17:

# Python program to update values in a dictionary.
my_dict = {"Name": "Mahika", "Age": 18}
print("Original dictionary: ", my_dict)

# Adding a nested key-value pair.
print("\nDictionary after adding nested key-value pair: ")
my_dict["Marks"] = {"Nested": {89, 90, 95}}
print(my_dict)
Output:
      Original dictionary:  {'Name': 'Mahika', 'Age': 18}

      Dictionary after adding nested key-value pair: 
      {'Name': 'Mahika', 'Age': 18, 'Marks': {'Nested': {89, 90, 95}}}

Update Element of Dictionary


Like other programming languages, Python also provides a built-in method named update() to update existing element in a dictionary. We can update a dictionary by adding a new element, entry, or key-value pair to an existing element or by deleting an existing element.

Example 18:

# Python program to update elements in a dictionary.
my_dict = {1: "Mango", 2: "Banana", 4: "Orange"}
print("Original dictionary: ")
print(my_dict)

# Updating an existing element or entry.
my_dict.update({3: "Apple"})
print("\nAfter updating of dictionary: ")
print(my_dict)
Output:
       Original dictionary: 
       {1: 'Mango', 2: 'Banana', 4: 'Orange'}

       After updating of dictionary: 
       {1: 'Mango', 2: 'Banana', 4: 'Orange', 3: 'Apple'}

Removing or Deleting Elements of Dictionary


Like other programming languages, Python also provides a facility to remove or delete elements from dictionaries. Python language provides three methods to remove elements of a dictionary. They are:

  • pop() method
  • popitem() method
  • clear() method

The pop() method removes an element of a dictionary with a specified key-value pair. Another method popitem() removes an element arbitrarily from the Python dictionary. While, the clear() method deletes all elements or entries from a dictionary.

Example 19:

# Python program to remove or delete elements of a dictionary.
my_dict = {1: "Mango", 2: "Banana", 3: "Orange", 4: "Apple", 5: "Guava"}
print("Original dictionary: ")
print(my_dict)

# Removing an element of a dictionary using pop() method.
removed_element = my_dict.pop(4)
print("\nElements of dictionary after removing: ")
print(my_dict)
print("Removed element: ", removed_element)

# Removing an element of a dictionary using popitem() method.
removed_element = my_dict.popitem()
print("\nElements of dictionary after removing: ")
print(my_dict)
print("Removed element: ", removed_element)

# Removing all elements of a dictionary.
my_dict.clear()
print(my_dict)
Output:
       Original dictionary: 
       {1: 'Mango', 2: 'Banana', 3: 'Orange', 4: 'Apple', 5: 'Guava'}

       Elements of dictionary after removing: 
       {1: 'Mango', 2: 'Banana', 3: 'Orange', 5: 'Guava'}
       Removed element:  Apple

       Elements of dictionary after removing: 
       {1: 'Mango', 2: 'Banana', 3: 'Orange'}
       Removed element:  (5, 'Guava')
       {}

If you want to delete a complete dictionary, use the del keyword.

Example 20:

# Python program to delete a complete dictionary.
my_dict = {1: "Mango", 2: "Banana", 3: "Apple"}
print("Original dictionary: ")
print(my_dict)

# Deleting a complete dictionary.
del my_dict
# Accessing after deleting dictionary.
print(my_dict)
Output:
      Original dictionary: 
      {1: 'Mango', 2: 'Banana', 3: 'Apple'}
      NameError: name 'my_dict' is not defined

As we have tried to access my_dict after deleting, so Python raised a NameError.

Advantage of using Dictionary in Python


There are the following advantages of using a dictionary in Python programming language. They are as:

(1) Dictionaries are mutable data types. Therefore, we can make any changes in the existing dictionary without creating a new dictionary object every time.

(2) They provide the flexibility or scalability in inserting or removing dictionary elements at runtime to the users.

(3) One of the major benefits of using a dictionary is that it allows to store heterogeneous data in a single dictionary.

(4) Dictionary is a dynamic in nature. Therefore, we do not need to define the size of a dictionary.

(5) It provides various functions to easily perform a different set of operations instead of writing long code.

(6) It is easy to use and understand dictionary data type as compared to other data types.

(7) It is easy to add or display values of the dictionary.


In this tutorial, you have known about Python dictionary with the help of various examples. Hope that you will have understood the basic key features of dictionaries and practiced all example programs.
Thanks for reading!!!

Please share your love