How to convert a python dictionary d = {1:10, 2:20, 3:30, 4:30}
to {10: [1], 20: [2], 30: [3, 4]}
?
I need to reverse a dictionary the values should become the keys of another dictionary and the values should be key in a list i.e. also in the sorted matter.
Use items() to Reverse a Dictionary in Python Printing a dictionary using items() will output an iterable list of tuple values that we can manipulate using the for loop for dictionaries. Reverse the key-value pairs by looping the result of items() and switching the key and the value.
1) Using OrderedDict() and items() method Later you make use of a reversed() function which is an in-built python method that takes an argument as the sequence data types like tuple, lists, dictionaries, etc and returns the reverse of it. Remember that reversed() method does not modify the original iterator.
keys() function to make your code more explicit. To get a list of the dictionary's values, you can call the dict. values() function.
Reversing keys and values in a python dict is a bit tricky. You should have in mind that a python dict must have a unique
keys.
So, if you know that when reversing keys and values of your current dict will have a unique keys, you can use a simple dict comprehension
like this example:
{v:k for k,v in my_dict.items()}
However, you can use groupby
from itertools
module like this example:
from itertools import groupby
a = {1:10, 2:20, 3:30, 4:30}
b = {k: [j for j, _ in list(v)] for k, v in groupby(a.items(), lambda x: x[1])}
print(b)
>>> {10: [1], 20: [2], 30: [3, 4]}
This use case is easily handled by dict.setdefault()
>>> d = {1:10, 2:20, 3:30, 4:30}
>>> e = {}
>>> for x, y in d.items():
e.setdefault(y, []).append(x)
>>> e
{10: [1], 20: [2], 30: [3, 4]}
An alternative is to use collections.defaultdict. This has a slightly more complex set-up, but the inner-loop access is simpler and faster than the setdefault approach. Also, it returns a dict subclass rather than a plain dict:
>>> e = defaultdict(list)
>>> for x, y in d.items():
e[y].append(x)
>>> e
defaultdict(<class 'list'>, {30: [3, 4], 10: [1], 20: [2]})
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