Sorting list of values in the returned dictionary in ascending order-Python
Question: Following functions return a reverse of the input dictionary where the values
of the original dictionary are used as keys for the returned dictionary and
the keys of the original dictionary are used as value for the returned
dictionary:

    
    
    def lower(d):
        return dict((k.lower(), [item.lower() for item in v]) for k, v in d.iteritems())
    
    def reverse_dictionary(input_dict):
        D=lower(input_dict)
        reverse_dict = {}
        for key, value in D.iteritems():
            if not isinstance(value, (list, tuple)):
                value = [value]
            for val in value:
                reverse_dict[val] = reverse_dict.get(val, [])
                reverse_dict[val].append(key)
        for key, value in reverse_dict.iteritems():
            if len(value) == 1:
                reverse_dict[key] = value[0]
    
        return reverse_dict
    input_dict= {'astute': ['Smart', 'clever', 'talented'], 
                'Accurate': ['exact', 'precise'], 
                'exact': ['precise'], 'talented': ['smart', 'keen', 'Bright'], 
                'smart': ['clever', 'bright', 'talented']}
    print(reverse_dictionary(input_dict))
    

But list of values in the returned dictionary is not sorted in ascending
order.

This function returns:

    
    
    {'precise': ['accurate', 'exact'], 'clever': ['astute', 'smart'], 'talented': ['astute', 'smart'], 'keen': 'talented', 'bright': ['talented', 'smart'], 'exact': 'accurate', 'smart': ['astute', 'talented']}
    

The correct output is:

    
    
    {'precise': ['accurate', 'exact'], 'clever': ['astute', 'smart'], 'talented': ['astute', 'smart'], 'keen': ['talented'], 'bright': ['smart', 'talented'], 'exact': ['accurate'], 'smart': ['astute', 'talented']}
    

Any help will be much appreciated.


Answer: `reverse_dict` is just a plain old dictionary, that does **not** retain the
order you add elements to it, rendering the entire method somewhat pointless.
Instead, if you wish to retain the order of insertion, you should use
`OrderedDict` from the `collections` module (`from collections import
OrderedDict`) when initializing this variable:

    
    
    reverse_dict = OrderedDict();
    

