PRVS
PRVS

Reputation: 1690

Sort value in dictionary by value in Python

I have something like this in Python to count the frequency of characters in a text, but i can't sort the values on the dictionary "v".

abcedario='abcdefghijklmnopqrstvuxwyz'
v = {}
count = 0
for c in abcedario:
    count = 0
    for char in text:
        if c == char:
            count = count +1
            v[c] = count
            sorted(v.items(), key=lambda x:x[1])
print v

I try to search here on stackoverflow but never solve my problem, the aspect of the output is this:

{'a': 2, 'b': 4, 'e': 4, 'd': 36, 'g': 31, 'f': 37, 'i': 14, 'h': 4, 'k': 51, 'j': 31, 'l': 34, 'n': 18, 'q': 13, 'p': 2, 'r': 9, 'u': 1, 't': 1, 'w': 36, 'v': 15, 'y': 14, 'x': 8, 'z': 10}

I want sort by value, so it's different from other posts.

Upvotes: 2

Views: 138

Answers (3)

LetzerWille
LetzerWille

Reputation: 5668

you can use Counter

from collections import Counter
text = "I have something like this in Python to count the frequency of characters in a text, but i can't sort the values on the dictionary"
print(Counter(text))

output:

Counter({' ': 24, 't': 15, 'e': 11, 'n': 9, 'h': 8, 'i': 8, 'o': 8, 'a': 7, 'c': 6, 's': 5, 'r': 5, 'u': 4, 'y': 3, 'f': 2, 'l': 2, 'v': 2, "'": 1, 'q': 1, 'd': 1, 'I': 1, 'm': 1, 'g': 1, 'b': 1, 'x': 1, ',': 1, 'P': 1, 'k': 1})

Upvotes: 2

Vlad
Vlad

Reputation: 18633

If you just want to print them in order, just print the output of sorted:

abcedario='abcdefghijklmnopqrstvuxwyz'
v = {}
count = 0
for c in abcedario:
    count = 0
    for char in text:
        if c == char:
            count = count +1
            v[c] = count
print sorted(v.items(), key=lambda x:x[1])

For text = "helloworld" you get:

[('e', 1), ('d', 1), ('h', 1), ('r', 1), ('w', 1), ('o', 2), ('l', 3)]  

Upvotes: 2

Ivana Balazevic
Ivana Balazevic

Reputation: 148

A python dictionary is an unordered collection of items. Therefore, it can't be sorted. Try looking into OrderedDict from collections.

Upvotes: 2

Related Questions