Sai A Sai A
Updated date Aug 28, 2023
In this blog, we will learn various methods to convert a Python dictionary with mixed data types into a dictionary containing only integer values. Explore methods like loops, dictionary comprehension, and more.

Introduction:

Dictionaries are a fundamental data structure in Python, allowing developers to store and manage key-value pairs efficiently. However, there might be scenarios where you need to transform a dictionary with various data types into a dictionary containing only integers. This blog explores the methods for converting a dictionary to a dictionary of integers in Python.

Method 1: Using a Loop

In this method. we achieve this conversion by iterating through the original dictionary and creating a new dictionary with integer values. Here's a sample Python program demonstrating this approach:

def convert_to_int_dict(input_dict):
    int_dict = {}
    for key, value in input_dict.items():
        int_value = int(value)
        int_dict[key] = int_value
    return int_dict

# Original dictionary with mixed data types
original_dict = {'a': '1', 'b': '2', 'c': '3'}

# Converting to a dictionary of integers
int_dict = convert_to_int_dict(original_dict)
print(int_dict)

Output:

{'a': 1, 'b': 2, 'c': 3}

In this method, we iterate through each key-value pair in the original dictionary and use the int() function to convert the value to an integer. Then, we store the key and integer value in the new integer dictionary.

Method 2: Dictionary Comprehension

Python offers a concise and elegant way to achieve the same result using dictionary comprehension. Here's how you can do it:

def convert_to_int_dict(input_dict):
    return {key: int(value) for key, value in input_dict.items()}

# Original dictionary with mixed data types
original_dict = {'a': '1', 'b': '2', 'c': '3'}

# Converting to a dictionary of integers using dictionary comprehension
int_dict = convert_to_int_dict(original_dict)
print(int_dict)

Output:

{'a': 1, 'b': 2, 'c': 3}

In this method, we use dictionary comprehension to directly create the new dictionary with integer values. The syntax is more compact compared to the loop-based approach.

Method 3: Using map() function

The map() function can be utilized to apply the int() function to each value in the original dictionary, returning an iterable that can be converted back to a dictionary. Here's how you can do it:

def convert_to_int(value):
    return int(value)

def convert_to_int_dict(input_dict):
    return dict(map(lambda item: (item[0], convert_to_int(item[1])), input_dict.items()))

# Original dictionary with mixed data types
original_dict = {'a': '1', 'b': '2', 'c': '3'}

# Converting to a dictionary of integers using map() function
int_dict = convert_to_int_dict(original_dict)
print(int_dict)

Output:

{'a': 1, 'b': 2, 'c': 3}

In this method, we define a separate function convert_to_int() to convert the value to an integer. Then, we use the map() function to apply this conversion to each value in the dictionary and finally convert the resulting iterable back into a dictionary.

Method 4: Handling Exception

If the original dictionary contains values that cannot be directly converted to integers, we need to handle exceptions to avoid program crashes. Here's an enhanced version of the loop-based approach that addresses this:

def convert_to_int_dict(input_dict):
    int_dict = {}
    for key, value in input_dict.items():
        try:
            int_value = int(value)
            int_dict[key] = int_value
        except ValueError:
            pass  # Ignore non-convertible values
    return int_dict

# Original dictionary with mixed data types
original_dict = {'a': '1', 'b': '2', 'c': 'hello'}

# Converting to a dictionary of integers with exception handling
int_dict = convert_to_int_dict(original_dict)
print(int_dict)

Output:

{'a': 1, 'b': 2}

In this method, we use a try-except block to catch the ValueError that might occur when trying to convert a non-integer value. The non-convertible values are simply ignored in the new integer dictionary.

Conclusion:

In this blog, we have explored several methods for converting a dictionary with mixed data types to a dictionary containing only integer values in Python. We have discussed using loops, dictionary comprehension, the map() function, and handling exceptions to accomplish this task.

Comments (0)

There are no comments. Be the first to comment!!!