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.
reverse_dict[key].sort()
then? – Martijn Pieters♦ Mar 13 '16 at 16:56