Sunday, November 17, 2024
Google search engine
HomeLanguagesPython Program To Convert dictionary values to Strings

Python Program To Convert dictionary values to Strings

Given dictionary with mixed data types as values, the task is to write a Python program to convert to parsed strings by different delims.

Examples:

Input : test_dict = {‘Gfg’ : 4, ‘is’ : “1”, ‘best’ : [8, 10], ‘geek’ : (10, 11, 2)}, list_delim, tuple_delim = ‘-‘, ‘^’
Output : {‘Gfg’: ‘4’, ‘is’: ‘1’, ‘best’: ‘8-10’, ‘geek’: ’10^11^2′}
Explanation : List elements are joined by -, tuples by ^ symbol.

Input : test_dict = {‘Gfg’ : 4, ‘is’ : “1”, ‘best’ : [8, 10], ‘geek’ : (10, 11, 2)}, list_delim, tuple_delim = ‘*’, ‘,’
Output : {‘Gfg’: ‘4’, ‘is’: ‘1’, ‘best’: ‘8*10’, ‘geek’: ‘10,11,2’}
Explanation : List elements are joined by *, tuples by , symbol.

Example: Using loop + isinstance() + join()

In this, we check for all the values data types using isinstance() and join using join() for difference delims, converting to parsed strings.

Python3




# Python3 code to demonstrate working of
# Convert dictionary values to Strings
# Using loop + isinstance()
 
# initializing dictionary
test_dict = {'Gfg' : 4,
             'is' : "1",
             'best' : [8, 10],
             'geek' : (10, 11, 2)}
              
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing delims
list_delim, tuple_delim = '-', '^'
 
res = dict()
for sub in test_dict:
     
    # checking data types
    if isinstance(test_dict[sub], list):
        res[sub] = list_delim.join([str(ele) for ele in test_dict[sub]])
    elif isinstance(test_dict[sub], tuple):
        res[sub] = tuple_delim.join(list([str(ele) for ele in test_dict[sub]]))
    else:
      res[sub] = str(test_dict[sub])
 
# printing result
print("The converted dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': 4, 'is': '1', 'best': [8, 10], 'geek': (10, 11, 2)}
The converted dictionary : {'Gfg': '4', 'is': '1', 'best': '8-10', 'geek': '10^11^2'}

Method #2: Using dictionary comprehension

Approach

Using dictionary comprehension with type checking

Algorithm

1. Define a function named convert_dict_values_to_strings that takes three parameters test_dict, list_delim, tuple_delim.
2. Create a new dictionary using dictionary comprehension.
3. Iterate over the key-value pairs in the input dictionary.
4. If the value is a list, join the list elements with the list_delim and add the resulting string to the new dictionary.
5. If the value is a tuple, join the tuple elements with the tuple_delim and add the resulting string to the new dictionary.
6. If the value is a string, add it as it is to the new dictionary.
7. If the value is of any other type, convert it to a string and add it to the new dictionary.
8. Return the new dictionary.

Python3




def convert_dict_values_to_strings(test_dict, list_delim, tuple_delim):
    # Create a new dictionary using dictionary comprehension
    # Iterate over the key-value pairs in the input dictionary
    # If the value is a list, join the list elements with the `list_delim` and add the resulting string to the new dictionary
    # If the value is a tuple, join the tuple elements with the `tuple_delim` and add the resulting string to the new dictionary
    # If the value is a string, add it as it is to the new dictionary
    # If the value is of any other type, convert it to a string and add it to the new dictionary
    new_dict = {k: list_delim.join(map(str, v)) if isinstance(v, list) else tuple_delim.join(map(str, v)) if isinstance(v, tuple) else str(v) for k, v in test_dict.items()}
    return new_dict
 
 
# Example
test_dict = {'Gfg' : 4, 'is' : '1', 'best' : [8, 10], 'geek' : (10, 11, 2)}
list_delim, tuple_delim = '-', '^'
print(convert_dict_values_to_strings(test_dict, list_delim, tuple_delim))


Output

{'Gfg': '4', 'is': '1', 'best': '8-10', 'geek': '10^11^2'}

Time Complexity: O(n*m), where n is the number of key-value pairs in the input dictionary and m is the size of the longest list or tuple value.
Auxiliary Space: O(n), for storing the new dictionary.

METHOD 3:Using re module.

APPROACH:

The above code is a Python program that converts the values of a given dictionary to strings. The program takes an original dictionary as input and creates a new dictionary with the same keys but with string values. The string values are obtained by converting the original values to strings and replacing commas with hyphens or carets for list or tuple values, respectively, using regular expressions.

ALGORITHM:

1.Initialize an empty dictionary called “converted_dict”
2.Loop through each key-value pair in the original dictionary
3.Convert the value to a string using the str() function
4.Use regular expressions to replace ‘,’ with ‘-‘ or ‘^’ for list or tuple values respectively
5.Add the key-value pair to the “converted_dict”
6.Return the “converted_dict”

Python3




import re
 
def convert_dict(original_dict):
    converted_dict = {}
    for key, value in original_dict.items():
        value_str = str(value)
        if isinstance(value, list):
            value_str = re.sub(r'(?<=\[)[^]]+(?=\])', lambda m: m.group(0).replace(',', '-'), value_str)
        elif isinstance(value, tuple):
            value_str = re.sub(r'(?<=\()[^)]+(?=\))', lambda m: m.group(0).replace(',', '^'), value_str)
        converted_dict[key] = value_str
    return converted_dict
 
# Example Usage
original_dict = {'Gfg': 4, 'is': '1', 'best': [8, 10], 'geek': (10, 11, 2)}
converted_dict = convert_dict(original_dict)
print(converted_dict)


Output

{'Gfg': '4', 'is': '1', 'best': '[8- 10]', 'geek': '(10^ 11^ 2)'}

Time Complexity: O(n) where n is the number of elements in the original dictionary
Space Complexity: O(n) where n is the number of elements in the original dictionary

METHOD 4: Using keys(), type(),list(),map(),join() methods

Approach:

  1.  Initiate a for loop to traverse over dictionary keys
  2. Check the type of each value if type is list convert the list to string list using list(),map() and then join using list_delim,if type is tuple convert the list to string list using list(),map() and then join using tuple_delim,if other type  convert to string using str() 
  3. Create a new dictionary res with keys same as test_dict and joined strings(using join())as values
  4. Display res

Python3




# Python3 code to demonstrate working of
# Convert dictionary values to Strings
# Using loop + type()
 
# initializing dictionary
test_dict = {'Gfg' : 4,'is' : "1",'best' : [8, 10],'geek' : (10, 11, 2)}
             
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing delims
list_delim, tuple_delim = '-', '^'
 
res = dict()
for i in list(test_dict.keys()):
    if type(test_dict[i]) is list:
        x=list(map(str,test_dict[i]))
        res[i]=list_delim.join(x)
    elif type(test_dict[i]) is tuple:
        y=list(map(str,test_dict[i]))
        res[i]=tuple_delim.join(y)
    else:
        res[i]=str(test_dict[i])
# printing result
print("The converted dictionary : " + str(res))


Output

The original dictionary is : {'Gfg': 4, 'is': '1', 'best': [8, 10], 'geek': (10, 11, 2)}
The converted dictionary : {'Gfg': '4', 'is': '1', 'best': '8-10', 'geek': '10^11^2'}

Time Complexity : O(N) N – length of dictionary test_dict
Auxiliary Space : O(N) N – length of dictionary res

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments