python字典按键值排序_在Python中按键或值按升序和降序对
字典排序
python字典按键值排序
Problem Statement: Write a Python program to sort (ascending and descending) a dictionary by key or value.
Problem Statement:
问题陈述:编写⼀个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:
算法:
1. Take a Dictionary.
拿字典。
2. Convert it in a list.
将其转换为列表。
3. Now sort the list in ascending or Descending order.
现在,按升序或降序对列表进⾏排序。
4. Convert again The sorted list to dictionary.
再次转换将排序列表转换为字典。
5. Print Output
打印输出python代码转换
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}
l=list(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
l=list(y.items())
l.sort(reverse=True) #sort in reverse order
print('Descending order is',l)
dict=dict(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 l=list(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 l.sort()
现在,在此之后,我们使⽤Sort函数,即l.sort()
Which sorts the list and after the one thing is important to convert again the list into Dictionary by dict=dict(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(reverse=True) You will get the sorted dictionary in descending order.
使⽤l.sort(reverse = True)您将获得降序排序的字典。
翻译⾃:
python字典按键值排序
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论