-1

I want to convert dictionary into a list of dictionary if the values are same. I have a sample data below:

my_dict={'Book 1':'Martha','Book 2':'Randy','Book 5':'Martha'}

Now I want to convert the above dictionary into the following output:

my_dict={'Randy':['Book 2'],'Martha':['Book 1','Book 5']}

How do I do this in python?

user86907
  • 817
  • 9
  • 21

3 Answers3

1

This should help u:

my_dict={'Book 1':'Martha','Book 2':'Randy','Book 5':'Martha'}

final_dict = {}

for key in my_dict.keys():
    final_dict.setdefault(my_dict[key],[]).append(key)
    
print(final_dict)

Output:

{'Martha': ['Book 1', 'Book 5'], 'Randy': ['Book 2']}
Sushil
  • 5,440
  • 1
  • 8
  • 26
1

Use a collections.defaultdict to group the keys by values:

from collections import defaultdict

my_dict={'Book 1':'Martha','Book 2':'Randy','Book 5':'Martha'}

d = defaultdict(list)
for k, v in my_dict.items():
    d[v].append(k)

print(d)

Output:

defaultdict(<class 'list'>, {'Martha': ['Book 1', 'Book 5'], 'Randy': ['Book 2']})
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
1

You could use the defaultdict function that is available. The code is as follows:

from collections import defaultdict

my_dict={'Book 1':'Martha','Book 2':'Randy','Book 5':'Martha'}
new_dict = defaultdict(list)
for i in my_dict:
    new_dict[my_dict[i]].append(i)

new_dict = dict(new_dict)
print(new_dict)
sotmot
  • 1,256
  • 2
  • 9
  • 21