I would like to write a function that receives a dictionary as input argument and returns 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 as explained below:
dict = {'Accurate': ['exact', 'precise'],
'exact': ['precise'],
'astute': ['Smart', 'clever'],
'smart': ['clever', 'bright', 'talented']}
to
dict = {'precise': ['accurate', 'exact'],
'clever': ['astute', 'smart'],
'talented': ['smart'],
'bright': ['smart'],
'exact': ['accurate'],
'smart': ['astute']}
The list of values in the returned dictionary should be sorted in ascending order. Capitalization does not matter. This means that all the words should be converted to lower case letters. For example the word "Accurate" is capitalized in the original dictionary but in the returned dictionary it is written with all lower case letters.
#My code is:
from collections import defaultdict
def reverse_dictionary(input_dict):
d = defaultdict(list)
for v,k in input_dict.items():
d[k].append(v)
return d
But it returns this error though:
Error in evaluating function:
TypeError at line 6
unhashable type: 'list'
Method #1 : Using OrderedDict() + reversed() + items() This method is for older versions of Python. Older versions don't keep order in dictionaries, hence have to converted to OrderedDict to execute this task.
To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse . Dictionaries are unordered data structures.
You can do it very simply like this:
newdict = {}
for key, value in olddict.items():
for string in value:
newdict.setdefault(string, []).append(key)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With