-2

So my question has been downvoted twice because the question is said to be a duplicate : Sort Counter by frequency, then alphabetically in Python

The answers here are speaking about ordering the Counter Dictionnary alphabetically. While what I want to order it in a ascending order

I want to do a order a list of strings by frequency. I get the frequency of each string in an descending order by default.

I did a letter_counts = Counter(list_of_string)) . I think I am getting a kind of dictionnary ordered in an descending order.

I want to sort them in an ascending order,** but i am not managing it so far.

I have read How do I sort a dictionary by value?, but cannot really apply it to a descending order.

frequency = Counter(list_of_string)
print(frequency)

The dictionary (is it?) I am getting is the following. As you can see it is already in a descending order

    Counter({' stan ': 3, 
' type ': 3, 
' quora ': 3, 
' pescaparian': 3, 
' python remove even number from a list': 3, 
' gmail': 3, 
' split words from a string ': 3, 
' split python ': 2, 
' split ': 2, 
' difference entre list et set': 2, 
' add a key to a dictionnary python': 1, 
' stackoverflowsearch python add lists': 1})
OrganicMustard
  • 1,158
  • 1
  • 15
  • 36
  • 1
    Isn't that in descending order? – roganjosh Dec 29 '18 at 01:28
  • In the example you referenced, the `sorted` built-in has a `reverse` keyword argument if you wanted to sort it in reverse. Docs: https://docs.python.org/3.7/library/functions.html?highlight=sorted#sorted – Adam Dec 29 '18 at 01:30
  • Hi Adam, yes thanks a a lot. Hi Roganjosh, i made a mistake and asked for a descending order instead of ascending, you are right. – OrganicMustard Dec 29 '18 at 12:05

1 Answers1

1

You better specify what python version you are using, as dictionaries had no order by Python 3.7 (practically by Python 3.6). Since, they are sorted by insertion order. If you are using an older version, maybe OrderedDict will help you. Anyhow, if you want to just print the keys or hold them in another data structure sorted in descending order, this should work:

frequency = Counter(list_of_string)
l = frequency.keys()
print(l)

For opposite order:

frequency = Counter(list_of_string)
l = [k for k in frequency.keys()][::-1]
print(l)

If you need it to be a dictionary:

frequency = Counter(list_of_string)
d = dict(frequency.most_common()[::-1])
print(d)
motyzk
  • 366
  • 3
  • 14