📜  Python – 按键的第 i 个索引值对字典列表进行排序

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

Python – 按键的第 i 个索引值对字典列表进行排序

给定字典列表,根据 Key 的第 i 个索引值对字典进行排序

方法 #1:使用 sort() + lambda

上述功能的组合可以用来解决这个问题。在此,我们在“key”参数驱动条件下使用 sort() 和 lambda函数执行排序任务。

Python3
# Python3 code to demonstrate working of 
# Sort Dictionary List by Key's ith Index value
# Using sort() + lambda
  
# initializing lists
test_list = [{"Gfg" : "Best", "for" : "Geeks"},
             {"Gfg" : "Good", "for" : "Me"},
             {"Gfg" : "Better", "for" : "All"}]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K 
K = "Gfg"
  
# initializing i 
i = 2
  
# using sort to perform sort(), lambda
# function drives conditions
res = sorted(test_list, key = lambda sub: sub[K][i])
  
# printing result 
print("List after sorting : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Sort Dictionary List by Key's ith Index value
# Using sort() + lambda + get()
  
# initializing lists
test_list = [{"Gfg" : "Best", "for" : "Geeks"},
             {"Gfg" : "Good", "for" : "Me"},
             {"Gfg" : "Better", "for" : "All"}]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K 
K = "Gfg"
  
# initializing i 
i = 2
  
# using sort to perform sort(), lambda
# function drives conditions, get() used to 
# avoid missing key error
res = sorted(test_list, key = lambda sub: sub.get(K)[i])
  
# printing result 
print("List after sorting : " + str(res))


输出

方法 #2:使用 sort() + lambda + get()

以上功能的组合也可以解决这个问题。这只是上述方法的轻微变化。在此,我们使用 get() 来避免特定记录中不存在密钥的机会。

Python3

# Python3 code to demonstrate working of 
# Sort Dictionary List by Key's ith Index value
# Using sort() + lambda + get()
  
# initializing lists
test_list = [{"Gfg" : "Best", "for" : "Geeks"},
             {"Gfg" : "Good", "for" : "Me"},
             {"Gfg" : "Better", "for" : "All"}]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K 
K = "Gfg"
  
# initializing i 
i = 2
  
# using sort to perform sort(), lambda
# function drives conditions, get() used to 
# avoid missing key error
res = sorted(test_list, key = lambda sub: sub.get(K)[i])
  
# printing result 
print("List after sorting : " + str(res))
输出