Skip to content
Related Articles

Related Articles

Improve Article

Python – Render Initials as Dictionary Key

  • Last Updated : 12 Nov, 2020

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

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :