Search code examples
pythondictionarytabularalphabetical

Sort a dictionary alphabetically, and print it by frequency


I am running python 2.7.2 on a mac.

I have a simple dictionary:

dictionary= {a,b,c,a,a,b,b,b,b,c,a,w,w,p,r}

I want it to be printed and have the output like this:

Dictionary in alphabetical order:
    a  4
    b  5
    c  2
    p  1
    r  1
    w  2

But what I'm getting is something like this...

a  1
a  1
a  1
a  1
b  1
.
.
.
w  1

This is the code I am using.

new_dict = []


    for word in dictionary.keys():
        value = dictionary[word]
        string_val = str(value)
        new_dict.append(word + ": " + string_val)

    sorted_dictionary = sorted(new_dict)

    for entry in sorted_dictionary:
        print entry

Can you please tell me where is the mistake? (By the way, I'm not a programmer but a linguist, so please go easy on me.)


Solution

  • What you're using is not a dictionary, it's a set! :)

    And sets doesn't allow duplicates.

    What you probably need is not dictionaries, but lists.

    A little explanation

    Dictionaries have keys, and each unique keys have their own values:

    my_dict = {1:'a', 2:'b', 3:'c'} 
    

    You retrieve values by using the keys:

    >>> my_dict [1]
    'a'
    

    On the other hand, a list doesn't have keys.

    my_list = ['a','b','c']
    

    And you retrieve the values using their index:

    >>> my_list[1]
    'b'
    

    Keep in mind that indices starts counting from zero, not 1.

    Solving The Problem

    Now, for your problem. First, store the characters as a list:

    l = ['a', 'b', 'c', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'a', 'w', 'w', 'p', 'r']
    

    Next, we'll need to know what items are in this list:

    items = []
    for item in l:
        if item not in items:
            items.append(item)
    

    This is pretty much equal to items = set(l) (the only difference is that this is a list). But just to make things clear, hope you understand what the code does.

    Here is the content of items:

    >>> items
    ['a', 'b', 'c', 'w', 'p', 'r']
    

    With that done, we will use lst.count() method to see the number of a char's occurence in your list, and the built-in function sorted() to sort the items:

    for item in sorted(items): #iterates through the sorted items.
        print item, l.count(item)
    

    Result:

    a 4
    b 5
    c 2
    w 2
    p 1
    r 1
    

    Hope this helps!!