python字典按键值排序_在Python中按键或值按升序和降序对字典排序
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} 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 dictionaryOutput
輸出量
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 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 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)您將獲得降序排序的字典。
翻譯自: https://www.includehelp.com/python/sorting-a-dictionary-in-ascending-and-descending-order-by-key-or-value-in-python.aspx
python字典按鍵值排序
總結
以上是生活随笔為你收集整理的python字典按键值排序_在Python中按键或值按升序和降序对字典排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VSRE的完整形式是什么?
- 下一篇: appweb ejs_EJS部分