# Sorting a dictionary in Ascending and Descending order by Key or Value in Python

Sorting a dictionary in Python: Here, we are going to learn how to sort a dictionary in ascending and descending order by key or value?
Submitted by Yash Khandelwal, on March 28, 2019

Problem Statement: Write a Python program to sort (ascending and descending) a dictionary by key or value.

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 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())

One Important function here is items(). What is this?

So In Python Dictionary, items() method is used to return the list with all dictionary keys with values.

Now after that, we use Sort function i.e. l.sort()

Which sorts the list and after the one thing is important to convert again the list into Dictionary by dict=dict(l)

So after that, we will get the sorted Dictionary in ascending order.

For doing all this in Descending order just do one thing i.e instead of l.sort()

use l.sort(reverse=True) You will get the sorted dictionary in descending order.