Reputation: 855
Lets say i have the following list of tuples:
[('test', {'key': 'testval1' }),
('test', {'key': 'testval2' }),
('test', {'key': 'testval3' }),
('test', {'key': 'testval4' }),
('foo', {'key': 'testval5' }),
('oof', {'key': 'testval6' }),
('qux', {'key': 'testval7' }),
('qux', {'key': 'testval8' })]
I want to filter and get a list of all values of second item object that have first item the 'test' string. So the output will be like:
['testval1','testval2','testval3','testval4']
Manage to get the test elements with Output = list(filter(lambda x:'test' in x, conditions)). But this returns me another list of tuples. How can i get the values of the second obj element without loop again ?
Upvotes: 0
Views: 50
Reputation: 1455
using Setdefault
output=[]
for item,dict in li:
if item == 'test':
var = dict.setdefault('key',{})
output.append(var)
print(output)
Upvotes: 0
Reputation: 4472
you can do
a = [('test', {'key': 'testval1' }), ('test', {'key': 'testval2' }), ('test', {'key': 'testval3' }), ('test', {'key': 'testval4' }), ('foo', {'key': 'testval5' }), ('oof', {'key': 'testval6' }), ('qux', {'key': 'testval7' }), ('qux', {'key': 'testval8' })]
print([i[1]['key'] for i in a if i[0] == 'test'])
list comprehension is a great method to filter such lists by adding the if after the list name.
or you can do it by filter and map
print([*map(lambda x: x[1]['key'], filter(lambda x: x[0] == 'test' in x, a))])
or
print(list(map(lambda x: x[1]['key'], filter(lambda x: x[0] == 'test' in x, a))))
All of them will output
['testval1', 'testval2', 'testval3', 'testval4']
Upvotes: 0
Reputation: 465
Using a single comprehension should do it :
[b['key'] for a, b in data if a == 'test']
(Assuming your list is data
)
Upvotes: 0
Reputation: 71517
>>> elements = [('test', {'key': 'testval1' }),
... ('test', {'key': 'testval2' }),
... ('test', {'key': 'testval3' }),
... ('test', {'key': 'testval4' }),
... ('foo', {'key': 'testval5' }),
... ('oof', {'key': 'testval6' }),
... ('qux', {'key': 'testval7' }),
... ('qux', {'key': 'testval8' })]
>>> [d['key'] for (s, d) in elements if s == 'test']
['testval1', 'testval2', 'testval3', 'testval4']
Upvotes: 2