 GeeksforGeeks App
Open App Browser
Continue

# Python – Render Initials as Dictionary Key

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.

Method #1 : Using loop

In this, we create each dictionary by getting initial element using string element access and render value as list element.

## Python3

 `# Python3 code to demonstrate working of``# Render Initials as Dictionary Key``# Using loop` `# initializing list``test_list ``=` `[``"geeksforgeeks"``, ``"is"``, ``"best"``]` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))` `res ``=` `dict``()``for` `ele ``in` `test_list:``    ` `    ``# assigning initials as key``    ``res[ele[``0``]] ``=` `ele` `# printing result``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)

Method #2 : Using dictionary comprehension

In this, we create dictionary using shorthand method similar to above method, to provide one liner alternative to actual problem.

## Python3

 `# Python3 code to demonstrate working of``# Render Initials as Dictionary Key``# Using dictionary comprehension` `# initializing list``test_list ``=` `[``"geeksforgeeks"``, ``"is"``, ``"best"``]` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))` `# constructing dictionary``res ``=` `{ele[``0``] : ele ``for` `ele ``in` `test_list}` `# printing result``print``(``"Constructed Dictionary : "` `+` `str``(res))`

Output

```The original list is : ['geeksforgeeks', 'is', 'best']
Constructed Dictionary : {'g': 'geeksforgeeks', 'i': 'is', 'b': 'best'}```

Method #3: Using the reduce function from the functools module.

Step-by-step approach:

1. 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.
2. Inside the construct_dict function, we add a new key-value pair to the dictionary dict_so_far using current_word as the key and current_word as the value. Then, we return the updated dictionary.
3. 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.
4. 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.
5. 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.
6. Finally, we print the constructed dictionary using the print() function.

## Python3

 `from` `functools ``import` `reduce` `# initializing list``test_list ``=` `[``"geeksforgeeks"``, ``"is"``, ``"best"``]` `# printing original list``print``(``"The original list is : "` `+` `str``(test_list))` `# Define a function to construct the dictionary``def` `construct_dict(dict_so_far, current_word):``    ``dict_so_far[current_word[``0``]] ``=` `current_word``    ``return` `dict_so_far` `# Call reduce with the function and list as arguments``res ``=` `reduce``(construct_dict, test_list, {})` `# printing result``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:

1. Import the defaultdict module from the collections library.
2. Initialize an empty defaultdict with the str function.
3. Iterate through each element of the input list using a for loop.
4. Extract the first character of each element and use it as a key to store the corresponding element in the defaultdict.
5. The defaultdict will automatically create a key with an empty string value if the key does not already exist.
6. Return the resulting defaultdict.

## Python3

 `from` `collections ``import` `defaultdict` `test_list ``=` `[``"geeksforgeeks"``, ``"is"``, ``"best"``]``# printing original list``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)))``#This code is contributed by Jyothi Pinjala`

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.

My Personal Notes arrow_drop_up