Given List of Strings, convert to dictionary with Key as initial value of values. Won’t work in cases having words with similar initials.
Input : test_list = [“geeksforgeeks”, “is”, “best”]
Output : {‘g’: ‘geeksforgeeks’, ‘i’: ‘is’, ‘b’: ‘best’}
Explanation : Keys constructed from initial character.
Input : test_list = [“geeksforgeeks”, “best”]
Output : {‘g’: ‘geeksforgeeks’, ‘b’: ‘best’}
Explanation : Keys constructed from initial character.
Render Initials as Dictionary Key Using loop
In this, we create each dictionary by getting initial element using string element access and render value as list element.
Python3
test_list = [ "geeksforgeeks" , "is" , "best" ]
print ( "The original list is : " + str (test_list))
res = dict ()
for ele in test_list:
res[ele[ 0 ]] = ele
print ( "Constructed Dictionary : " + str (res))
|
Output
The original list is : ['geeksforgeeks', 'is', 'best']
Constructed Dictionary : {'g': 'geeksforgeeks', 'i': 'is', 'b': 'best'}
Time Complexity: O(n), where n is the number of elements in the input list.
Auxiliary Space: O(n)
Render Initials as Dictionary Key Using dictionary comprehension
In this, we create dictionary using shorthand method similar to above method, to provide one liner alternative to actual problem.
Python3
test_list = [ "geeksforgeeks" , "is" , "best" ]
print ( "The original list is : " + str (test_list))
res = {ele[ 0 ] : ele for ele in test_list}
print ( "Constructed Dictionary : " + str (res))
|
Output
The original list is : ['geeksforgeeks', 'is', 'best']
Constructed Dictionary : {'g': 'geeksforgeeks', 'i': 'is', 'b': 'best'}
Render Initials as Dictionary Key Using the reduce function from the functools module.
Step-by-step approach:
- Define a function construct_dict(dict_so_far, current_word) that takes two arguments: dict_so_far, which is a dictionary that accumulates the key-value pairs as we process each element in test_list, and current_word, which is the current word being processed.
- Inside the construct_dict function, we add a new key-value pair to the dictionary dict_so_far using current_word[0] as the key and current_word as the value. Then, we return the updated dictionary.
- Call the reduce function from the functools module, passing construct_dict as the function to apply to each element in test_list, test_list as the list to apply the function to, and an empty dictionary {} as the initial value of the accumulator.
- The reduce function iterates over the list test_list, calling construct_dict with the current element and the current value of the accumulator (which is initially an empty dictionary), and updates the accumulator with the key-value pair returned by construct_dict.
- After all elements in test_list have been processed, reduce returns the final value of the accumulator, which is a dictionary where the keys are the first letters of the words in test_list and the values are the corresponding words.
- Finally, we print the constructed dictionary using the print() function.
Python3
from functools import reduce
test_list = [ "geeksforgeeks" , "is" , "best" ]
print ( "The original list is : " + str (test_list))
def construct_dict(dict_so_far, current_word):
dict_so_far[current_word[ 0 ]] = current_word
return dict_so_far
res = reduce (construct_dict, test_list, {})
print ( "Constructed Dictionary : " + str (res))
|
Output
The original list is : ['geeksforgeeks', 'is', 'best']
Constructed Dictionary : {'g': 'geeksforgeeks', 'i': 'is', 'b': 'best'}
Time complexity: O(n), where n is the length of the input list, since we only need to iterate over the list once.
Auxiliary space: O(n), since we need to create a dictionary with n key-value pairs.
Method #4: Using loop and defaultdict with tuple as default value:
Algorithm:
- Import the defaultdict module from the collections library.
- Initialize an empty defaultdict with the str function.
- Iterate through each element of the input list using a for loop.
- Extract the first character of each element and use it as a key to store the corresponding element in the defaultdict.
- The defaultdict will automatically create a key with an empty string value if the key does not already exist.
- Return the resulting defaultdict.
Python3
from collections import defaultdict
test_list = [ "geeksforgeeks" , "is" , "best" ]
print ( "The original list is : " + str (test_list))
res = defaultdict( str )
for ele in test_list:
res[ele[ 0 ]] = ele
print ( "Constructed Dictionary : " + str ( dict (res)))
|
Output
The original list is : ['geeksforgeeks', 'is', 'best']
Constructed Dictionary : {'g': 'geeksforgeeks', 'i': 'is', 'b': 'best'}
Time Complexity: O(n), where n is the length of the input list. This is because we only iterate through the list once.
Auxiliary Space: O(n), where n is the length of the input list. This is because we create a dictionary with n key-value pairs. However, the space complexity can be slightly higher due to the overhead of using a defaultdict instead of a regular dictionary.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
27 Jul, 2023
Like Article
Save Article