网站建设的想法和意见,做网站语言知乎,阜阳网站优化,做海外网站交税吗python字典按键值排序Problem Statement: Write a Python program to sort (ascending and descending) a dictionary by key or value. 问题陈述#xff1a;编写一个Python程序#xff0c;以按键或值对字典进行排序(升序和降序)。 Example: 例#xff1a; Input: diction…python字典按键值排序Problem Statement: Write a Python program to sort (ascending and descending) a dictionary by key or value. 问题陈述编写一个Python程序以按键或值对字典进行排序(升序和降序)。 Example: 例 Input:
dictionary {carl:40,alan:2,bob:1,danny:3}
Output:
Ascending order is {alan: 2, bob: 1, carl:40), danny:3}
Descending order is {danny: 3, carl: 40, bob: 1, alan:2}
Algorithm: 算法 Take a Dictionary. 拿字典。 Convert it in a list. 将其转换为列表。 Now sort the list in ascending or Descending order. 现在按升序或降序对列表进行排序。 Convert again The sorted list to dictionary. 再次转换将排序列表转换为字典。 Print Output 打印输出 Python代码按升序和降序对字典进行排序 (Python code to sort a dictionary in ascending and descending order) #you can take the input as integers also this
#will work for that also for eg:{1:2,3:4,4:3,2:1,0:0}
y{carl:40,alan:2,bob:1,danny:3}
llist(y.items()) #convet the given dict. into list
#In Python Dictionary, items() method is used to return the list
#with all dictionary keys with values.
l.sort() #sort the list
print(Ascending order is,l) #this print the sorted list
llist(y.items())
l.sort(reverseTrue) #sort in reverse order
print(Descending order is,l)
dictdict(l) # convert the list in dictionary
print(Dictionary,dict) #the desired output is this sorted dictionary
Output 输出量 Ascending order is [(alan, 2), (bob, 1), (carl, 40), (danny, 3)]
Descending order is [(danny, 3), (carl, 40), (bob, 1), (alan, 2)]
Dictionary {bob: 1, carl: 40, alan: 2, danny: 3}
Explanation of Code: 代码说明 In this, we just learn how to sort the dictionaries by key or values. So to do this the best approach is to convert the entire dictionary into a list. To convert this we have used this llist(y.items()) 在这里我们只学习如何按键或值对字典进行排序。 因此最好的方法是将整个词典转换为列表。 为了转换它我们使用了l list(y.items()) One Important function here is items(). What is this? 这里的一个重要功能是items() 。 这是什么 So In Python Dictionary, items() method is used to return the list with all dictionary keys with values. 因此在Python字典中 items()方法用于返回带有所有带有值的字典键的列表。 Now after that, we use Sort function i.e. l.sort() 现在在此之后我们使用Sort函数即l.sort() Which sorts the list and after the one thing is important to convert again the list into Dictionary by dictdict(l) 对列表进行排序然后一件事很重要即通过dict dict(l)将列表再次转换为Dictionary So after that, we will get the sorted Dictionary in ascending order. 因此在那之后我们将按升序获得排序后的Dictionary。 For doing all this in Descending order just do one thing i.e instead of l.sort() 对于以降序执行所有这些操作只需做一件事即可即代替l.sort() use l.sort(reverseTrue) You will get the sorted dictionary in descending order. 使用l.sort(reverse True)您将获得降序排序的字典。 翻译自: https://www.includehelp.com/python/sorting-a-dictionary-in-ascending-and-descending-order-by-key-or-value-in-python.aspxpython字典按键值排序