Reputation: 661
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. 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?
Upvotes: 1
Views: 65
Reputation: 4963
You can also do it as follows
attr2 = [v[2] for v in inputDatasets.values()]
Upvotes: 0
Reputation: 22766
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:
attr2 = list(map(lambda b:b[2], inputDatasets.values()))
Upvotes: 3