Javatpoint Logo
Javatpoint Logo

Some Advance Ways to Use Python Dictionaries

In this tutorial, we will explain some important and exciting use cases of dictionaries. The dictionary is the most important and useful data structure that stores the key-value pair and it is flexible, efficient, and easy to use. Although dictionaries in Python are typically used for tasks such as counting frequency, mapping values, or organizing data, there are a variety of creative and unexpected ways in which they can be utilized. This article aims to delve into ten unique and unconventional uses of Python dictionaries that you may have yet to consider. Let's see some exciting use of the dictionary.

  • Memoization
  • Spars Matrices
  • Counters
  • XML/HTML Parser
  • Configuration Files
  • Caching API Response
  • State Machines
  • Encoding and Decoding Data


Memoization is a method used to improve the performance of costly function calls by storing the output of previous function calls in a cache. In Python, we can utilize a dictionary to implement memoization. This is done by defining a dictionary where the function arguments serve as keys, and the corresponding function outputs serve as values. Before executing the function, we can check whether the result is already present in the dictionary, and if so, retrieve the cached output instead of recomputing the function. Let's understand the following example.

Example -

Explanation -

The above code first defines the expensive function, representing a time-consuming computation we want to optimize using memoization. It then creates an empty cache dictionary to store the function results.

The memoized_function() takes an argument and first checks if the result for that argument is already present in the cache. If it is, the cached output is retrieved and returned. If it is not, the expensive_function() is called to compute the function output, which is then stored in the cache for future use. The function ultimately returns the calculated result.

Sparse Matrices

A sparse matrix is a matrix in which most elements are zero. Given that storing all of the zeros in the matrix would be inefficient, a dictionary can be utilized to store only the non-zero elements. In this approach, the keys in the dictionary are tuples consisting of the indices of the non-zero matrix elements, while the values are the non-zero elements themselves.

Example &ndash

Explanation -

The sparse_matrix dictionary contains a representation of a sparse matrix. In this specific example, the matrix has three non-zero elements.

The first non-zero element is located in the matrix's first row and first column, corresponding to the key (0, 0) in the dictionary. The value associated with this key is 1, indicating that the element at row 0 and column 0 of the matrix is 1.

The second non-zero element is located in the matrix's second row and third column, corresponding to the key (1, 2) in the dictionary. The value associated with this key is 3, indicating that the element at row 1 and column 2 of the matrix is 3.

The third non-zero element is located in the matrix's third row and second column, corresponding to the key (2, 1) in the dictionary. The value associated with this key is 5, indicating that the element at row 2 and column 1 of the matrix is 5.

By utilizing a dictionary to store only the non-zero elements of the matrix, we can save the memory and computation time that would have been required to store and manipulate the zero elements.


Count the frequency of combinations of elements is a useful technique using dictionaries in Python. It can be accomplished by creating a dictionary where the keys are the combinations of elements we want to count, and the values are the corresponding frequencies.

For example, if we have a list of words and want to count the frequency of each pair of words that appear together, we can use a dictionary to accomplish this. Let's understand the following example.

Example -

Explanation -

In the above code, we create an empty dictionary called pair_freq and then loop through the list of words, creating a tuple of each pair of adjacent words. It then checks if the pair already exists in the dictionary, and if it does, it increments its frequency by 1. If the pair doesn't exist in the dictionary, it adds it with a frequency of 1.

At the end of the loop, the dictionary pair_freq contains the frequency of each pair of adjacent words in the original list. We can adapt this approach to counting the frequency of other combinations of elements, such as triplets or n-tuples.

XML/HTML Parsing

In Python, tags are used in XML and HTML documents that can be represented as nested dictionaries. We can use the xmltodict library to convert XML documents into Python dictionaries. Let's see the following XML document.

Example -

We can convert this XML document into a Python dictionary using the xmltodict library with the following code.

Example -


    'book': {
        'title': 'Python Tricks',
        'author': 'Dan Bader',
        'publisher': 'Real Python',
        'published_on': '2017-06-03'

Explanation -

In the above code, we import the xmltodict library, which provides the parse() function that can be used to convert an XML string into a Python dictionary. The XML document is represented as a string in the xml_str variable.

After parsing the XML string using xmltodict.parse(), the resulting Python dictionary is stored in the book_dict variable. The print() function is then used to display the contents of the dictionary on the console.

As we can see, the XML tags are represented as keys in the resulting dictionary, and their values are the contents of the tags. If there are nested tags in the XML document, they will be represented as nested dictionaries in the resulting Python dictionary.

Configuration Files

In Python, dictionaries can serve as a convenient way to store configuration options for a program. We can define a dictionary with default values, and then modify or override those values by loading a configuration file. Let's understand the following example.

Example -

In this case, DEFAULT_CONFIG is a dictionary with four key-value pairs, each representing a configuration option with a default value.

To load a configuration file and modify the values in the dictionary, you can use a library like configparser.

Example -

In this code, configparser is used to load a configuration file named myprogram.ini. The configuration file is assumed to have a section named [myprogram] that contains key-value pairs representing configuration options.

The values in the DEFAULT_CONFIG dictionary are then updated with values from the configuration file if they exist. The default value is used if a configuration option is not specified in the configuration file.

This way, we can easily modify the behavior of your Python program by specifying configuration options in a configuration file without having to modify the program's code.

Caching API Response

To avoid making unnecessary requests when working with APIs, it can be helpful to cache responses for future use. We can achieve it by using dictionaries as a simple cache, where you can map API requests to their corresponding responses.

To make API requests in Python, you can use a library like requests. Here's an example of how to use a dictionary to cache API responses.

Example -


In this code, an empty dictionary cache is created to store the API responses. The get_api_data() function is defined to make API requests and cache the responses.

The function checks if the requested API URL is already in the cache dictionary. If it is, the function returns the cached response. If the requested URL is not in the cache, the function makes an API request using the requests library, and stores the response in the cache dictionary for future use.

By using a dictionary as a cache, we can avoid making redundant API requests and speed up the overall performance of our program.

State Machines

A state machine is a computational model used to describe the behavior of systems that can be in one of several states. In Python, we can represent a state machine using a dictionary, where the keys represent the states and the values are also dictionaries that map input symbols to the next state.

Here's an example of how to represent a state machine using a Python dictionary:

Example -

In the above code, the state_machine is a dictionary representing a simple state machine with three states: 'state_A', 'state_B', and 'state_C'. The nested dictionaries define the possible transitions between states based on the input symbols' symbol_1' and 'symbol_2'.

For example, if the current state is 'state_A' and the input symbol is 'symbol_1', the next would be 'state_B'. If the input symbol is 'symbol_2', the next state would be 'state_C'.

To use this state machine, you would first set the initial state and then use the input symbols to transition between states.



Encoding and Decoding Data

Dictionaries are a useful tool for encoding and decoding data between different formats in Python. One way to use a dictionary for this purpose is to encode a JSON object as a query string or decode a query string into a JSON object.

To encode a JSON object as a query string using a dictionary, you can use the urllib.parse.urlencode() function, which takes a dictionary of key-value pairs and returns a query string.

Example -



Explanation -

In the above code, the json_obj dictionary represents a JSON object with three key-value pairs. The urllib.parse.urlencode() function encodes the JSON object as a query string.

To decode a query string into a JSON object using a dictionary, you can use the urllib.parse.parse_qs() function, which takes a query string and returns a dictionary of key-value pairs:

Example -


'{"name": ["John Doe"], "age": ["30"], "city": ["New York"]}'

Explanation -

In this example, the query_string variable represents a query string with three key-value pairs. The urllib.parse.parse_qs() function is used to decode the query string into a dictionary of key-value pairs, which is then converted to a JSON object using the json.dumps() function.

Using a dictionary to encode and decode data between different formats can be a powerful tool in Python, allowing you to work with data in a variety of formats without having to write custom encoding and decoding functions for each one.


Dictionaries are a versatile and powerful data structure in Python, with many unexpected uses beyond simple key-value mapping. They can represent complex data structures, such as graphs and state machines, and for caching API responses and encoding/decoding data between different formats.

In summary, understanding the full potential of dictionaries in Python can help you write more efficient, concise, and expressive code while improving your applications' performance and scalability.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA