What is the best way to sort on frequency?

Hi
What is the best way to sort on frequency?

ie.
I want to sort the list below based on the frequency of the key of the dictionary.
There are four elements with "c" as the key so elements with "c" goes to the top.
then "a", then "b"
 list = [
        { "a": "a1"  },
        { "b": "b1"  },
        { "c": "c1"  },
        { "a": "a2"  },
        { "a": "a3"  },
        { "c": "c2"  },
        { "c": "c3"  },
        { "c": "c4"  },
        { "b": "b2"  }
     ]

Open in new window

sorts to
 list = [
        { "c": "c1"  },
        { "c": "c2"  },
        { "c": "c3"  },
        { "c": "c4"  },
        { "a": "a1"  },
        { "a": "a2"  },
        { "a": "a3"  },
        { "b": "b1"  },
        { "b": "b2"  }
     ]

Open in new window


Thanks
Jamie
jamie_lynnAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gelonidaCommented:
Well not sure, whether there's something more elegant, but what I would do is to
first create an intermediate dict storing the frequency for each key.

this could be done with following code snippet
freq = {}
for entry in lst:
    key = entry.keys()[0]
    freq[key] = freq.get(key, 0) + 1

Open in new window


then you can sort with
 this one has random order for values with same key
#sorted_lst = sorted(lst, key=lambda entry:
                freq[entry.keys()[0]], reverse=True)

# next statements sorts within same key by the value
sorted_lst = sorted(lst, key=lambda entry:
                (-freq[entry.keys()[0]], entry.values()[0]))

Open in new window



Comment: I renamed list into lst, as list is a reserved python keyword. In any real code one should (in my opinion) try to avoid overloading keywords, one might have quite funny surprises.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jamie_lynnAuthor Commented:
Works great! thanks!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Python

From novice to tech pro — start learning today.