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:

算法:

  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 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 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,人工智能,深度学习,小程序)