📜  Python程序按键长度对字典进行排序

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

Python程序按键长度对字典进行排序

给定字典,按其键长度排序。

方法 #1:使用 len() + sort() + 字典理解 + items()

在这里,我们使用 sort() 执行排序任务,items() 用于从字典中获取元组对,len() 获取键长度。然后字典理解执行转换回字典的任务。

Python3
# Python3 code to demonstrate working of 
# Sort Dictionary by Key Lengths
# Using len() + sort() + dictionary comprehension + items()
  
def get_len(key):
    return len(key[0])
  
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# sorting using sort()
# external to render logic 
test_dict_list = list(test_dict.items())
test_dict_list.sort(key = get_len)
  
# reordering to dictionary
res = {ele[0] : ele[1]  for ele in test_dict_list}
  
# printing result 
print("The sorted dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Sort Dictionary by Key Lengths
# Using sorted() + lambda function + items() + dictionary comprehension
  
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# sorting using sorted()
# lambda fnc. to render logic 
test_dict_list = sorted(list(test_dict.items()), key = lambda key : len(key[0]))
  
# reordering to dictionary
res = {ele[0] : ele[1]  for ele in test_dict_list}
  
# printing result 
print("The sorted dictionary : " + str(res))


输出:

方法 #2:使用 sorted() + lambda函数+ items() + 字典理解

在这里,我们使用 sorted() 执行排序任务,lambda函数用于提供获取键长度的逻辑。

蟒蛇3

# Python3 code to demonstrate working of 
# Sort Dictionary by Key Lengths
# Using sorted() + lambda function + items() + dictionary comprehension
  
# initializing dictionary
test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# sorting using sorted()
# lambda fnc. to render logic 
test_dict_list = sorted(list(test_dict.items()), key = lambda key : len(key[0]))
  
# reordering to dictionary
res = {ele[0] : ele[1]  for ele in test_dict_list}
  
# printing result 
print("The sorted dictionary : " + str(res)) 

输出: