Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sorted dictionary?
#1
Hi experts,

This is a short one Smile Just wondering if there is a way to sort the print out of a dictionary. For example, if I print the dictionary, I got the result like:
{2: 16, 5: 22, 4: 20, 6: 13, 3: 19, 1: 10}
Can we make it like:

{1:10,2:16,3:19,4:20,5:22,6:13}
Really appreciate your help!

Best Regards,
Henry
Reply
#2
Actually python will print your dictionary ordered, as default order key is dictionary key and here are integer numbers. But, if you want it explicit you can use such code to order by key:

sorted(d.iteritems(), key=lambda x: x[0])
to order by value:

sorted(d.iteritems(), key=lambda x: x[1])
Reply
#3
In Python 3 you can get an ordered dictionary by insertion order. For the previous versions, you have to use https://docs.python.org/3/library/collec...rderedDict.

Jupyter QtConsole 4.3.0
Python 3.6.4 (default, Dec 23 2017, 19:07:07) ##### 
Type "copyright", "credits" or "license" for more information.

IPython 5.4.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

d = {2: 16, 5: 22, 4: 20, 6: 13, 3: 19, 1: 10}

dict(sorted(d.items()))
Out[2]: {1: 10, 2: 16, 3: 19, 4: 20, 5: 22, 6: 13}

sorted_d = dict(sorted(d.items()))

sorted_d
Out[4]: {1: 10, 2: 16, 3: 19, 4: 20, 5: 22, 6: 13}
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Failing to print sorted files tester_V 4 1,245 Nov-12-2022, 06:49 PM
Last Post: tester_V
  set and sorted, not working how expected! wtr 2 1,281 Jan-07-2022, 04:53 PM
Last Post: bowlofred
  How to make elements return sorted? notsoexperienced 4 3,218 Sep-24-2020, 09:00 AM
Last Post: perfringo
  Why is my original list also sorted? Pedroski55 1 1,609 Jul-15-2020, 09:25 PM
Last Post: Yoriz
  Outputting Sorted Text files Help charlieroberrts 1 1,723 Jul-05-2020, 08:37 PM
Last Post: menator01
  sorted function example mystery sabaidii2 4 2,540 Feb-10-2020, 09:37 AM
Last Post: DeaD_EyE
  Byte array is sorted when sending via USB daviddlc68 1 2,819 Aug-16-2019, 10:11 AM
Last Post: wavic
  sorted object in list trois 2 2,247 Mar-04-2019, 09:12 AM
Last Post: trois
  [Help] sorted() in while loop with user's input() {Screenshot attached} vanicci 5 4,007 Aug-04-2018, 08:59 PM
Last Post: vanicci
  understanding sorted key parameter amirt 2 2,757 Jul-30-2018, 06:27 PM
Last Post: amirt

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020