Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting a counter in python by keys

I have a counter that looks a bit like this:

Counter: {('A': 10), ('C':5), ('H':4)} 

I want to sort on keys specifically in an alphabetical order, NOT by counter.most_common()

is there any way to achieve this?

like image 453
corvid Avatar asked Jul 29 '13 17:07

corvid


People also ask

Can we sort counter in Python?

Counting Sort Algorithm. In this tutorial, you will learn about the counting sort algorithm and its implementation in Python, Java, C, and C++. Counting sort is a sorting algorithm that sorts the elements of an array by counting the number of occurrences of each unique element in the array.

What does counter () do in Python?

Counter is a subclass of dict that's specially designed for counting hashable objects in Python. It's a dictionary that stores objects as keys and counts as values. To count with Counter , you typically provide a sequence or iterable of hashable objects as an argument to the class's constructor.


Video Answer


1 Answers

Just use sorted:

>>> from collections import Counter >>> counter = Counter({'A': 10, 'C': 5, 'H': 7}) >>> counter.most_common() [('A', 10), ('H', 7), ('C', 5)] >>> sorted(counter.items()) [('A', 10), ('C', 5), ('H', 7)] 
like image 66
falsetru Avatar answered Sep 20 '22 21:09

falsetru