Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse a dictionary (whose values are lists) in Python?

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'
like image 344
Utsav Maniar Avatar asked Mar 11 '16 16:03

Utsav Maniar


People also ask

How do you reverse a dictionary element in Python?

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.

How do you sort a dictionary in python?

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.


1 Answers

You can do it very simply like this:

newdict = {}
for key, value in olddict.items():
    for string in value:
        newdict.setdefault(string, []).append(key)
like image 154
zondo Avatar answered Nov 15 '22 15:11

zondo