Reputation: 165
Say I have a dictionary like this:
animals_dict =
{'cat': ['black', 'white', 'orange'],
'dog': ['black', 'white'],
'parrot': ['orange', 'green']}
And I want to get this:
colors_dict =
{'black': ['cat', 'dog'],
'white': ['cat', 'dog'],
'orange': ['cat', 'parrot'],
'green': ['parrot']}
The obvious way is to cycle through each animal in animals_dict; cycle through each of its colors; and add the animal to that color in colors_dict. But if you have tens of millions of animals and each animal can have up to a hundred colors, this will get computationally expensive. Is there a more efficient way to achieve this?
Upvotes: 1
Views: 242
Reputation: 39
index = {'cat': ['black', 'white', 'orange'],'dog': ['black', 'white'],'parrot': ['orange', 'green']}
new_dic = {}
for k,v in index.items():
for x in v:
new_dic.setdefault(x,[]).append(k)
print(new_dic)
This gives
{
'black': ['cat', 'dog'],
'white': ['cat', 'dog'],
'orange': ['cat', 'parrot'],
'green': ['parrot']
}
pythonic way to reverse a dict where values are lists? / How to reverse a dictionary (whose values are lists) in Python?
Upvotes: 3