Create a file in python
Question: Now i know how to implement a dictionary by file txt. So i have create the
example.txt (generic file) :

    
    
    aaa.12
    bbb.14
    ccc.10
    

and to make a dictionary:

    
    
    with open('example.text') as f:
        hash = {}
        for line in f:
            key, value = line.strip().split('.', 1)
            hash[key] = int(value)
    

So now i want to order my elemen by value: so i try

    
    
    with open('example.txt') as f:
        hash = {}
        for line in f:
            key, value = line.strip().split('.', 1)
            hash[key] = int(value)
            print hash #this print my dict
            value_sort=sorted(hash.values())
            print value:sort #to check the what return and gave me in this case value_sort=[10, 12, 14]
    

perfect so now how can i write on example.txt my items order by value:

    
    
    ccc.10
    aaa.12
    bbb.14
    


Answer: You'll need to loop through the `hash` dict separately, where you ask it to be
sorted on value:

    
    
    from operator import itemgetter
    
    hash = {}
    with open('example.text') as f:
        for line in f:
            key, value = line.strip().split('.', 1)
            hash[key] = int(value)
    
    for key, value in sorted(hash.items(), key=itemgetter(1)):
        print '{0}.{1}'.format(key, value)
    

The `sorted()` call is given a key to sort by, namely the second element of
each `.items()` tuple (a key and value pair).

If you wanted to _write_ the sorted items to a file, you'd need to open that
file in writing mode:

    
    
    with open('example.txt', 'w') as f:
        for key, value in sorted(hash.items(), key=itemgetter(1)):
            f.write('{0}.{1}\n'.format(key, value))
    

Note that we write newlines (`\n`) after every entry; `print` includes a
newline for us but when writing to a file you need to include it manually.

