简体   繁体   English

使用一对列表中的部分而非全部元素创建多个字典

[英]Creating multiple dicts using some but not all elements from a pair of lists

I would like, from a pair of lists, say: 我想从一对清单中说:

a = ['str1', 'str2', 'str3', 'str4', 'str5']
b = [var1, var2, var3, var4, var5]

to be able to create multiple dictionaries, with arbitrarily selected pairs of elements from a (as keyword) and b (as value). 能够创建多个字典,并从a(作为关键字)和b(作为值)中任意选择元素对。 I have found in a comment on an answer to this question , the following method: 我在对这个问题的答案的评论中发现以下方法:

full_set = dict(zip(a,b))
subset = {i:full_set[i] for i in a if i not in ['str2', 'str5']}

which produces subset dictionary: 产生子集字典:

{'str1': var1, 'str3': var3, 'str4': var4}

This works fine, but I am curious as to whether there is an equally short or shorter method of building subset dictionaries from the two lists, eg via specifying the list indices for the elements I want included, without creating a full dictionary containing all elements first. 这很好用,但是我对从两个列表中构建子集字典是否有同样短或短的方法感到好奇,例如通过为我要包含的元素指定列表索引,而无需先创建包含所有元素的完整字典。

For context, my vars refer to scikit-learn estimator objects. 对于上下文,我的var指的是scikit-learn估计器对象。

You can combine both statements into one: 您可以将两个语句合并为一个:

avoid = {'str2', 'str5'} # Sets have better lookup time :)
{k:v for k,v in zip(a,b) if k not in avoid}

Probably convert this to numpy arrays and use fancy indexing like this: 可能将其转换为numpy数组,并使用像这样的花式索引:

import numpy as np

a = np.array(['str1', 'str2', 'str3', 'str4', 'str5'])
b = np.array([1,2,3,4,5])

indices = [0, 1, 4]

d = dict(zip(a[indices],b[indices]))

d returns: d返回:

{'str1': 1, 'str2': 2, 'str5': 5}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 根据某些键/值对从合并列表中合并dicts - Merge dicts from a list of dicts based on some key/value pair 将列表的字典转换为字典中所有元素的所有组合的字典列表的最有效方法? - Most pythonic way to convert a dict of lists into a list of dicts of all combs of the elements in the lists from the dict? 如果其他元素使用理解力匹配,则从两个字典列表中提取元素 - Extracting elements from two lists of dicts if other elements match using comprehension 从具有相同键的多个字典创建列表 - Create lists from multiple dicts with same key 访问嵌套列表和dicts中的所有元素,无需递归 - visit all elements in nested lists and dicts without recursion 如果在至少一个列表中不存在键值对,则从两个字典列表之一中查找并删除该字典 - Find and remove the dict from one of two lists of dicts if there is a key-value pair not present in at least one of the lists 使用带有另一个列表列表中的元素的操作创建列表列表 - Creating a list of lists using operations with elements from another list of lists 使用列表和字典从字典显示一些Django模板值 - Display some values with Django templates from dict with lists and dicts 从字典列表中查找相似的键值元素 - Find similar key-value elements from lists of dicts 配对来自两个不同列表的元素 - Pair elements from two different lists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM