[英]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;显而易见的方法是循环遍历animals_dict中的每一个动物; cycle through each of its colors;
循环通过它的每一种颜色; and add the animal to that color in colors_dict.
并将动物添加到 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? pythonic方式来反转一个值是列表的字典? / How to reverse a dictionary (whose values are lists) in Python?
/ 如何在 Python 中反转字典(其值是列表)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.