Reputation: 914
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.
Upvotes: 1
Views: 620
Reputation: 55933
If you want the values lists to be sorted, you'll need to do so explicitly.
This should work:
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] = sorted(value)
Upvotes: 0
Reputation: 1128
You can directly iterate over the sorted (key, value) pairs:
for key, value in sorted(D.iteritems()):
...
Or sort the values once the reversed dictionary has been constructed:
for key, value in reverse_dict.iteritems():
value.sort()
...
Upvotes: 0
Reputation: 312267
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();
Upvotes: 1