Python Forum
Help with syntax to sort dictionary by value
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help with syntax to sort dictionary by value
#1
I finally figured this out, but I'm not totally understanding why it works.

I created my dictionary (d) with keys and values. Now I need to print out the dictionary sorted from most to least occurrences:

sortedbyval = list() #creating empty list that will include sorted values
for key, val in list(d.items()):
    sortedbyval.append((val, key))

sortedbyval.sort(reverse=True)

for key, val in sortedbyval:
    print(key, val)
I understand that key and val are arbitrary counter variables. I think what confuses me most is the word "list." I initially had line 1 as

sortedbyval = ()

Why is that not sufficient to define an empty list?

Then, I had line 2 as

for key, val in sortedbyval(d.items()):

With "list" being a data structure type (I think), why should the syntax include "list" instead of the actual list name? Would the latter not make sense because at line 2, there are no key, val in sortedbyval since sortedbyval is still empty?

If you can shed any light on this then I'd appreciate it!
Reply
#2
First of all, sortedbyval = () creates a tuple, not a list. You can't append to a tuple. You can create a new empty list with sortedbyval = []. Note howthat uses brackets instead of parentheses.

As for for key, val in sortedbyval(d.items()):, where sortedbyval is a list, this is attempting to call the list as if it was a function. But sortedbyval is a list, not a function. On the other hand, list is a function that creates a new list from an iterable. On the gripping hand, you don't need either one. for key, val in d.items(): works just fine. Indeed, by not converting the d.items() generator into a list, it is more efficient.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to sort a list without .sort() function letmecode 3 3,419 Dec-28-2020, 11:21 PM
Last Post: perfringo
  Invalid syntax defining a dictionary? ep595 6 5,078 Nov-19-2019, 08:06 PM
Last Post: ThomasL
  [split] Manual Sort without Sort function fulir16 2 3,157 Jun-02-2019, 06:13 AM
Last Post: perfringo
  Manual Sort without Sort function dtweaponx 26 48,936 Jun-01-2019, 06:02 PM
Last Post: SheeppOSU

Forum Jump:

User Panel Messages

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