How can I sort a dictionary by key in python

0 votes
What would be a nice way to go from {2:3, 1:89, 4:5, 3:0} to {1:89, 2:3, 3:0, 4:5}?
I checked some posts but they all use the "sorted" operator that returns tuples.
Dec 28, 2020 in Python by anonymous
• 10,480 points
1,129 views

3 answers to this question.

0 votes

Standard Python dictionaries are unordered. Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict in a way that would preserve the ordering.

The easiest way is to use OrderedDict, which remembers the order in which the elements have been inserted:

In [1]: import collections

In [2]: d = {2:3, 1:89, 4:5, 3:0}

In [3]: od = collections.OrderedDict(sorted(d.items()))

In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])

Never mind the way od is printed out; it'll work as expected:

In [11]: od[1]
Out[11]: 89

In [12]: od[3]
Out[12]: 0

In [13]: for k, v in od.iteritems(): print k, v
   ....: 
1 89
2 3
3 0
4 5

Python 3

For Python 3 users, one needs to use the .items() instead of .iteritems():

In [13]: for k, v in od.items(): print(k, v)
   ....: 
1 89
2 3
3 0
4 5
answered Dec 28, 2020 by Gitika
• 65,770 points
0 votes
Load the Dictionary and perform the following operations:

First, sort the keys alphabetically using key_value.iterkeys() function.
Second, sort the keys alphabetically using sorted (key_value) function & print the value corresponding to it.
Third, sort the values alphabetically using key_value.iteritems(), key = lambda (k, v) : (v, k))

Displaying the Keys Alphabetically:
Examples:

Input:
key_value[2] = '64'       
key_value[1] = '69'
key_value[4] = '23'
key_value[5] = '65'
key_value[6] = '34'
key_value[3] = '76'

Output:
1 2 3 4 5 6
Program:

# Function calling
def dictionairy():  
 # Declare hash function       
 key_value ={}     
  
# Initializing value  
 key_value[2] = 56       
 key_value[1] = 2
 key_value[5] = 12
 key_value[4] = 24
 key_value[6] = 18      
 key_value[3] = 323
  
 print ("Task 1:-\n")
 print ("Keys are")
   
 # iterkeys() returns an iterator over the  
 # dictionary’s keys.
 for i in sorted (key_value.keys()) :  
     print(i, end = " ")
  
def main():
    # function calling
    dictionairy()              
      
# Main function calling
if __name__=="__main__":       
    main()
Output:
Task 1:-

Keys are
1 2 3 4 5 6
answered Dec 28, 2020 by Carlos
0 votes
Another way could be:
color_dict = {'red':'#FF0000',
          'green':'#008000',
          'black':'#000000',
          'white':'#FFFFFF'}

for key in sorted(color_dict):
    print("%s: %s" % (key, color_dict[key]))

Sample Output:

black: #000000                                                                                                
green: #008000                                                                                                
red: #FF0000                                                                                                  
white: #FFFFFF
answered Dec 28, 2020 by Thomas Walenta

Related Questions In Python

0 votes
1 answer

How can I add new keys to a dictionary in Python?

Yes, it is possible to add new ...READ MORE

answered Feb 9, 2022 in Python by Nandini
• 5,480 points
590 views
+3 votes
7 answers

How can I rename a file in Python?

yes, you can use "os.rename" for that. ...READ MORE

answered Mar 31, 2018 in Python by DareDev
• 6,890 points
20,081 views
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,440 points
1,339 views
+2 votes
2 answers

In a list of dictionaries, how can I find the minimum calue in a common dictionary field.

There are several options. Here is a ...READ MORE

answered Apr 10, 2018 in Python by charlie_brown
• 7,720 points
1,433 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,466 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,127 views
0 votes
1 answer

I want to download a file from the website by web scraping. Can anyone explain how to do this in jupyter lab (python) with an example?

Hey, Web scraping is a technique to automatically ...READ MORE

answered Apr 7, 2020 in Python by Gitika
• 65,770 points
2,423 views
+1 vote
4 answers

How do I remove an element from a list by index in Python?

Delete the List and its element: We have ...READ MORE

answered Jun 7, 2020 in Python by sahil
• 500 points
280,914 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP