简体   繁体   中英

Efficient way to get from {key1: [value1, value2...]} to {value1: [key1, key2...]}

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM