[英]Get a list of values from lists in a dictionary in Python
I created a dictionary in the following format with keys and a list of attributes associated with each key: 我用以下格式创建了一个字典,其中包含键和与每个键关联的属性列表:
inputDatasets = {
"data1": ["Path to data 1", "Attribute1", "Attribute2", "Attribute3"],
"data2": ["Path to data 2", "Attribute1", "Attribute2", "Attribute3"],
}
I would like to get a list of all the "Attribute2" contained in the dictionary. 我想获得字典中包含的所有“Attribute2”的列表。 For now I use:
现在我使用:
attr2 = []
for a, b in inputDatasets.items():
attr2.append(b[2])
But is there a more elegant way to do that? 但有更优雅的方式吗?
You could use a list comprehension, looping only through the values instead of key-value pairs: 您可以使用列表推导,仅通过值而不是键值对进行循环:
attr2 = [b[2] for b in inputDatasets.values()]
Alternatively, but not as elegantly, a map
with a lambda
could be useful: 或者,但不是那么优雅,带有
lambda
的map
可能很有用:
attr2 = list(map(lambda b:b[2], inputDatasets.values()))
你也可以这样做
attr2 = [v[2] for v in inputDatasets.values()]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.