Python – 排序字典忽略键
有时,在使用Python字典时,我们可能会遇到需要对字典元素进行排序的问题。这很简单,但有时我们可能会有某些杂散键,我们不希望在排序时改变它们的顺序。这适用于Python >= 3.6,因为键在此版本以后的字典中排序。这可以在数据域中应用。让我们讨论一种可以执行此任务的方式。
Input : test_dict = {“*-*” : “stray”, 70 : ‘is’}
Output : {“*-*” : “stray”, 70 : ‘is’}
Input : test_dict = {54 : “gfg”, “*-*” : “stray”, 20 : ‘best’}
Output : {20: ‘best’, ‘*-*’: ‘stray’, 54: ‘gfg’}
方法:使用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))
The original dictionary is : {45: ‘is’, 12: ‘gfg’, 100: ‘best’, ‘*-*’: ‘stray’, 150: ‘geeks’, 120: ‘for’}
The dictionary after sorting : {12: ‘gfg’, 45: ‘is’, 100: ‘best’, ‘*-*’: ‘stray’, 120: ‘for’, 150: ‘geeks’}