Python : filter list items from list of dictionary -
names = ['vapp1', 'vapp3', 'vapp4', 'vapp2'] vapps = [{'name':'vapp2', 'ip': '11.21.18.24', 'obj': 'obj523'}, {'name':'vapp3', 'ip': '11.21.18.27', 'obj': 'obj234'}, {'name':'vapp5', 'ip': '11.21.18.25', 'obj': 'obj246'}] result = [vapp vapp in vapps if vapp['name'] in names] print result
using list/dict comprehension getting want in result. want print vapp1
& vapp4
not there in vapps
.
what efficient way ? or how avoid looping achieve of filtered list of dictionary names common in list names
. , can print names not there.
you could abuse short-circuiting of and
so:
>>> result = [vapp vapp in vapps if ... vapp['name'] in names , ... (names.remove(vapp['name']) or 1)] >>> names # contains names not found in vapps ['vapp1', 'vapp4']
this yield same result list before, , modifies names
removes found vapp names side effect.
this works because and
clause evaluated when first part of statement (vapp['name'] in names
) true
. or 1
part needed because .remove()
yields none
, false
in boolean context.
list comprehensions side effects discouraged bad style, though - , names
list modified, better save copy if need again.
generally, not worry performance, , use 2 loops - or write out in readable, classic loop.
Comments
Post a Comment