📜  Python - 将姓名首字母渲染为字典键

📅  最后修改于: 2022-05-13 01:54:26.551000             🧑  作者: Mango

Python - 将姓名首字母渲染为字典键

给定字符串列表,将键转换为字典作为值的初始值。在单词首字母相似的情况下不起作用。

方法#1:使用循环

在此,我们通过使用字符串元素访问获取初始元素并将值呈现为列表元素来创建每个字典。

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))


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))


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

方法#2:使用字典理解

在此,我们使用类似于上述方法的速记方法创建字典,为实际问题提供一种线性替代方法。

蟒蛇3

# 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))
输出
The original list is : ['geeksforgeeks', 'is', 'best']
Constructed Dictionary : {'g': 'geeksforgeeks', 'i': 'is', 'b': 'best'}