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
153 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,970 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

+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
15,710 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
500 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,780 points
542 views
0 votes
1 answer

How can I convert a list of dictionaries from a CSV into a JSON object in Python?

You could try using the AST module. ...READ MORE

answered Apr 17, 2018 in Python by anonymous
2,421 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 2,484 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,810 points
1,863 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,970 points
911 views
0 votes
4 answers

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

1886 Use del and specify the index of the element ...READ MORE

answered Dec 11, 2020 in Python by Gitika
• 65,970 points
112,005 views