📜  Python – 排序字典忽略键

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

Python – 排序字典忽略键

有时,在使用Python字典时,我们可能会遇到需要对字典元素进行排序的问题。这很简单,但有时我们可能会有某些杂散键,我们不希望在排序时改变它们的顺序。这适用于Python >= 3.6,因为键在此版本以后的字典中排序。这可以在数据域中应用。让我们讨论一种可以执行此任务的方式。

方法:使用next() + sorted() + insert()
以上方法的结合,可以用来解决这个问题。在此,我们使用 sorted() 进行排序,insert() 用于在其位置插入流浪元素,next() 用于在初始流浪键的情况下按顺序获取下一个键。

# Python3 code to demonstrate working of 
# Sort Dictionary ignoring Key
# Using next() + sorted() + insert()
  
# initializing dictionary
test_dict = {45 : 'is', 12 : 'gfg', 100 : 'best', 
             "*-*" : "stray", 150 : 'geeks', 120 : 'for'}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# strary key 
stray_key = '*-*'
  
# Sort Dictionary ignoring Key
# Using next() + sorted() + insert()
temp = next(idx for idx, val in enumerate(test_dict) if val == stray_key)
idx = sorted(ele for ele in test_dict if ele != stray_key)
idx.insert(temp, stray_key)
res = {ele: test_dict[ele] for ele in idx}
  
# printing result 
print("The dictionary after sorting : " + str(res)) 
输出 :