Sunday, November 17, 2024
Google search engine
HomeLanguagesPython | Converting list string to dictionary

Python | Converting list string to dictionary

Yet another problem regarding the interconversion between data types is conversion of string of list to a dictionary of keys and values. This particular problem can occur at the places where we need huge amount of string data to be converted to dictionary for preprocessing in Machine Learning domain. Let’s discuss certain ways in which this task can be done. 

Method #1 : Using dictionary comprehension + split() Dictionary comprehension can be used for construction of dictionary and split function can be used to perform the necessary splits in list to get the valid key and value pair for dictionary. 

Python3




# Python3 code to demonstrate
# Converting list string to dictionary
# Using dictionary comprehension + split()
 
# initializing string
test_string = '[Nikhil:1, Akshat:2, Akash:3]'
 
# printing original string
print("The original string : " + str(test_string))
 
# using dictionary comprehension + split()
# Converting list string to dictionary
res = {sub.split(":")[0]: sub.split(":")[1] for sub in test_string[1:-1].split(", ")}
 
# print result
print("The dictionary after extraction is : " + str(res))


Output : 

The original string : [Nikhil:1, Akshat:2, Akash:3]
The dictionary after extraction is : {'Nikhil': '1', 'Akash': '3', 'Akshat': '2'}

Time complexity: O(n*n), where n is the length of the test_list. The dictionary comprehension + split() takes O(n*n) time
Auxiliary Space: O(n), where n is the number of elements in the test_string

  Method #2 : Using eval() + replace() This particular task can also be performed using the combination of above two functions, the eval and replace functions. In this method, eval function performs like dictionary comprehension, constructing the dictionary and replace function performs the necessary replaces. This function is used when keys and values has to be converted to integer. 

Python3




# Python3 code to demonstrate
# Converting list string to dictionary
# Using eval() + replace()
 
# initializing string
test_string = '[120:1, 190:2, 140:3]'
 
# printing original string
print("The original string : " + str(test_string))
 
# using eval() + replace()
# Converting list string to dictionary
res = eval(test_string.replace("[", "{").replace("]", "}"))
 
# print result
print("The dictionary after extraction is : " + str(res))


Output : 

The original string : [120:1, 190:2, 140:3]
The dictionary after extraction is : {120: 1, 140: 3, 190: 2}

 Method #3: Using a for loop: You can use a for loop to iterate through the list string, extract the key-value pairs, and add them to a dictionary.

Python3




test_string = '[Nikhil:1, Akshat:2, Akash:3]'  # Initialize the list string
 
print("The original string:", test_string)  # Print the original string
 
res = {}  # Initialize an empty dictionary
 
# Iterate through the key-value pairs in the list string
for pair in test_string[1:-1].split(','):  # Split the string on the comma character, and ignore the first and last characters (the square brackets)
    key, value = pair.split(':'# Split the key-value pair on the colon character
    res[key] = int(value)  # Add the key and value to the dictionary, converting the value to an integer
 
print("The dictionary after extraction:", res)  # Print the resulting dictionary
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original string: [Nikhil:1, Akshat:2, Akash:3]
The dictionary after extraction: {'Nikhil': 1, ' Akshat': 2, ' Akash': 3}

In this approach, the list string is first split on the comma character to get a list of key-value pairs. Then, a for loop iterates through the key-value pairs, splits each pair on the colon character to extract the key and value, and adds them to the dictionary. The value is converted to an integer before being added to the dictionary.

The time complexity of this approach is O(n), where n is the length of the list string. The space complexity is also O(n), as the dictionary will have n key-value pairs.

Method #4: Using regular expressions
We can also use regular expressions to extract the key-value pairs from the list string and construct the dictionary.

In this approach, we use the regular expression module to define a pattern that matches the key-value pairs in the list string. We then use the findall() method of the regular expression module to find all matches of the pattern in the string. The findall() method returns a list of tuples, where each tuple contains the key and value as separate elements. Finally, we convert the list of tuples to a dictionary using the built-in dict() function.

Python3




import re # Import the regular expressions module
 
test_string = '[Nikhil:1, Akshat:2, Akash:3]' # Initialize the list string
 
print("The original string:", test_string) # Print the original string
 
pattern = r'(\w+):(\d+)' # Define a regular expression pattern to match the key-value pairs
matches = re.findall(pattern, test_string) # Find all matches of the pattern in the string
 
res = dict(matches) # Convert the list of matches to a dictionary
 
print("The dictionary after extraction:", res) # Print the resulting dictionary


Output

The original string: [Nikhil:1, Akshat:2, Akash:3]
The dictionary after extraction: {'Nikhil': '1', 'Akshat': '2', 'Akash': '3'}

The time complexity of this approach is O(n), where n is the length of the list string. The auxiliary space is also O(n), as the dictionary will have n key-value pairs. The regular expression pattern also has a time complexity of O(n), but this is usually negligible compared to the time complexity of the findall() method.

RELATED ARTICLES

Most Popular

Recent Comments