Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Convert String List to Key-Value List dictionary

Python – Convert String List to Key-Value List dictionary

Given a string, convert it to key-value list dictionary, with key as 1st word and rest words as value list.

Input : test_list = [“gfg is best for Lazyroar”, “CS is best subject”] 
Output : {‘gfg’: [‘is’, ‘best’, ‘for’, ‘Lazyroar’], ‘CS’: [‘is’, ‘best’, ‘subject’]} 
Explanation : 1st elements are paired with respective rest of words as list. 

Input : test_list = [“gfg is best for Lazyroar”] 
Output : {‘gfg’: [‘is’, ‘best’, ‘for’, ‘Lazyroar’]} 
Explanation : 1st elements are paired with respective rest of words as list.

Method #1 : Using split() + loop

In this, we iterate for each string, and then perform split of string using split(), assign 1st element as key and pack other elements into list, using * operator and create key-value list pair.

Python3




# Python3 code to demonstrate working of
# Convert String List to Key-Value List dictionary
# Using split() + loop
 
# initializing list
test_list = ["gfg is best for Lazyroar", "I love gfg", "CS is best subject"]
 
# printing string
print("The original list : " + str(test_list))
 
 
res = dict()
for sub in test_list:
     
    # split() for key
    # packing value list
    key, *val = sub.split()
    res[key] = val
 
# printing results
print("The key values List dictionary : " + str(res))


Output

The original list : ['gfg is best for Lazyroar', 'I love gfg', 'CS is best subject']
The key values List dictionary : {'gfg': ['is', 'best', 'for', 'Lazyroar'], 'I': ['love', 'gfg'], 'CS': ['is', 'best', 'subject']}

Time Complexity: O(n2) -> (loop +split)
Space Complexity: O(n)

Method #2 : Using split() + dictionary comprehension

This is similar way to solve this problem. In this, dictionary comprehension is used to solve this problem.

Python3




# Python3 code to demonstrate working of
# Convert String List to Key-Value List dictionary
# Using split() + dictionary comprehension
 
# initializing list
test_list = ["gfg is best for Lazyroar", "I love gfg", "CS is best subject"]
 
# printing string
print("The original list : " + str(test_list))
 
# using dictionary comprehension to solve this problem
res = {sub[0] : sub[1:] for sub in (ele.split() for ele in test_list)}
 
# printing results
print("The key values List dictionary : " + str(res))


Output

The original list : ['gfg is best for Lazyroar', 'I love gfg', 'CS is best subject']
The key values List dictionary : {'gfg': ['is', 'best', 'for', 'Lazyroar'], 'I': ['love', 'gfg'], 'CS': ['is', 'best', 'subject']}

Time Complexity: O(n2)
Space Complexity: O(n)

Method 3: Using map(), lambda function and split()

Algorithm:

  1. Define the input list of strings test_list.
  2. Create a lambda function that splits each string into a list of words, takes the first word as the key, and the remaining words as the value.
  3. Apply the lambda function to each element of test_list using the map() function to create a list of tuples.
  4. Convert the list of tuples into a dictionary using the dict() function.
  5. Print the original list and the resulting dictionary.
     

Python3




test_list = ["gfg is best for Lazyroar", "I love gfg", "CS is best subject"]
# printing string
print("The original list : " + str(test_list))
 
# using map(), lambda function and split()
res = dict(map(lambda x: (x.split()[0], x.split()[1:]), test_list))
 
# printing result
print("The key values List dictionary : " + str(res))


Output

The original list : ['gfg is best for Lazyroar', 'I love gfg', 'CS is best subject']
The key values List dictionary : {'gfg': ['is', 'best', 'for', 'Lazyroar'], 'I': ['love', 'gfg'], 'CS': ['is', 'best', 'subject']}

The time complexity of this algorithm is O(nk), where n is the number of strings in the input list and k is the average number of words in each string. This is because the map() function and the lambda function are applied once to each string in the list, which takes O(k) time for each string. The dict() function also takes O(n) time to convert the list of tuples to a dictionary.
The auxiliary space of the algorithm is O(nk) because the resulting dictionary contains all the words from the input strings.

Method #4: Using regex and dictionary comprehension

This method uses regular expressions to split each string in test_list into words and create a dictionary using dictionary comprehension.

Step-by-step approach:

  • Import the re module for regular expressions.
  • Initialize an empty dictionary result.
  • Use a list comprehension to split each string in test_list into words using the re.findall() function.
  • Use a dictionary comprehension to create a dictionary from the list of key-value pairs, where the keys are the first words of each string and the values are the lists of remaining words.
  • Assign the resulting dictionary to the result variable.

Below is the implementation of the above approach:

Python3




import re
 
# initializing list
test_list = ["gfg is best for Lazyroar", "I love gfg", "CS is best subject"]
 
# printing string
print("The original list : " + str(test_list))
 
# using regex and dictionary comprehension to solve this problem
result = {s[0]: re.findall(r'\w+', s)[1:] for s in test_list}
 
# printing results
print("The key values List dictionary : " + str(result))


Output

The original list : ['gfg is best for Lazyroar', 'I love gfg', 'CS is best subject']
The key values List dictionary : {'g': ['is', 'best', 'for', 'Lazyroar'], 'I': ['love', 'gfg'], 'C': ['is', 'best', 'subject']}

Time complexity: O(n), where n is the number of strings in test_list.
Auxiliary space: O(n), where n is the total number of words in all the strings in test_list.

Method #5: Using list comprehension and dictionary

Step-by-step approach:

  • Initialize the list of strings test_list.
  • Print the original list using the print() function.
  • Use a dictionary comprehension to iterate over each string s in test_list.
  • Split each string s using the split() method, which returns a list of words.
  • Use the first word in the list as the key in the resulting dictionary, and use the remaining words as the corresponding values.
  • Print the resulting dictionary using the print() function.

Below is the implementation of the above approach:

Python3




# initializing list
test_list = ["gfg is best for Lazyroar", "I love gfg", "CS is best subject"]
 
# printing string
print("The original list : " + str(test_list))
 
# using list comprehension and dictionary to solve this problem
result = {s.split()[0]: s.split()[1:] for s in test_list}
 
# printing results
print("The key values List dictionary : " + str(result))


Output

The original list : ['gfg is best for Lazyroar', 'I love gfg', 'CS is best subject']
The key values List dictionary : {'gfg': ['is', 'best', 'for', 'Lazyroar'], 'I': ['love', 'gfg'], 'CS': ['is', 'best', 'subject']}

Time complexity: O(n), where n is the number of strings in test_list.
Auxiliary space: O(n*m), where n is the number of strings in test_list and m is the maximum number of words in a string.

Method 6 : using the reduce function from the functools module. 

The reduce function applies a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.

 step by step approach:

Import the reduce function from the functools module.
Define a function combine_dicts that takes two dictionaries as arguments and returns their combination. The combination is achieved by adding the values of the second dictionary to the corresponding keys in the first dictionary.
Split each string in test_list into words using the split() function.
Create a list of dictionaries, where each dictionary has one key-value pair. The key is the first word in the string, and the value is a list of the remaining words in the string.
Use the reduce function to combine the dictionaries in the list using the combine_dicts function defined in step 2.
Print the resulting dictionary.

Python3




# importing reduce function
from functools import reduce
 
# initializing list
test_list =  ["gfg is best for Lazyroar", "I love gfg", "CS is best subject"]
 
# printing string
print("The original list : " + str(test_list))
 
# defining function to combine dictionaries
def combine_dicts(dict1, dict2):
    for key in dict2:
        if key in dict1:
            dict1[key].extend(dict2[key])
        else:
            dict1[key] = dict2[key]
    return dict1
 
# splitting strings into words and creating list of dictionaries
dict_list = [{s.split()[0]: s.split()[1:]} for s in test_list]
 
# using reduce function to combine dictionaries
result_dict = reduce(combine_dicts, dict_list)
 
# printing results
print("The key values List dictionary : " + str(result_dict))


Output

The original list : ['gfg is best for Lazyroar', 'I love gfg', 'CS is best subject']
The key values List dictionary : {'gfg': ['is', 'best', 'for', 'Lazyroar'], 'I': ['love', 'gfg'], 'CS': ['is', 'best', 'subject']}

The time complexity of this solution is O(nk), where n is the number of elements in test_list and k is the maximum number of words in a string in test_list. 
The space complexity is also O(nk), since we need to store the resulting dictionary and the list of dictionaries.

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