Skip to content
Related Articles
Open in App
Not now

Related Articles

Python – Render Initials as Dictionary Key

Improve Article
Save Article
Like Article
  • Last Updated : 12 Nov, 2020
Improve Article
Save Article
Like Article

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'}

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'}


My Personal Notes arrow_drop_up
Like Article
Save Article

Start Your Coding Journey Now!