I am just wondering how i would convert a string, such as "hello there hi there", and turn it into a dictionary, then using this dictionary, i want to count the number of each word in the dictionary, and return it in alphabetic order. So in this case it would return:
[('hello', 1), ('hi', 1), ('there', 2)]
any help would be appreciated
>>> from collections import Counter
>>> text = "hello there hi there"
>>> sorted(Counter(text.split()).items())
[('hello', 1), ('hi', 1), ('there', 2)]
class collections.Counter([iterable-or-mapping])
A
Counter
is adict
subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. TheCounter
class is similar to bags or multisets in other languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With