简体   繁体   English

从 {key1: [value1, value2...]} 到 {value1: [key1, key2...]} 的有效方法

[英]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.

相关问题 从字典 1 中提取 key1:value1 和从字典 2 中提取 key1:value1,将它们分配给 4 个不同的变量,循环 - Extract key1:value1 from dictionary 1 and key1:value1 from dictionary 2, assign them to 4 different variables, loop 将两个 JSON {key1:value1 , key2:value2} 组合成单个键(即 {key3:value1,value2})Python - combining two JSON {key1:value1 , key2:value2} to single key (i e {key3:value1,value2}) Python 如何将字典的格式更改为value1; key1; 在Python 3.6中? - How do I change the format of a dictionary to value1;key1; in Python 3.6? 如果 key1 不存在,Python dict 获取 key2 值的最简单和最干净的方法 - Python dict easiest and cleanest way to get value of key2 if key1 is not present 如何从python中key1的最大值列表中找到key2的最小值的对象 - how to find object of min value of key2 from list of max values of key1 in python 在Python中将(键,值)(键,值)映射到(键,(值1,值2)) - Mapping (key, value) (key, value) to (key, (value1, value2)) in Python 使用key = value1,... valuen格式在python中编写文件 - Writing a file in python in a key=value1,…valuen format 给定dict1 key2时查找dict1 key1的值? - Find value of dict1 key1 when given dict1 key2? 如何将 key1、key2 值组合分配给新的 Pandas Dataframe,其中 Key 1 和 Key 作为索引,Header - How can I assign a key1, key2 value combination to a new Pandas Dataframe with Key 1 and Key as Index and Header “if key1 or key2 are not in dict”的简洁写法 Python - Terse way of writing "if key1 or key2 are not in dict" Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM