do_something() if 2 in [x.get('arm_id') for x in tcp_packet['red']] else None
题
I've a json list:
tcp_packet = {'green': [], 'red': [{'arm_id': 2, 'pptl_id': [1]}, {'arm_id': 1, 'pptl_id': [1]}]}
I need to check whether arm_id exists in 'red' or not?
currently i have to loop around tcp_packet['red']
to find out whether arm_id = 2
exists or not?
for i in tcp_packet[color]:
if '2' in i.keys():
do something
is there a one-line solution to this?
解决方案
其他提示
It's a bit unclear from your question, but is this what you are looking for?
>>> tcp_packet = {'green': [], 'red': [{'arm_id': 2, 'pptl_id': [1]}, {'arm_id': 1, 'pptl_id': [1]}]}
>>> any((('arm_id', 2) in i.iteritems()) for i in tcp_packet['green'])
False
>>> any((('arm_id', 2) in i.iteritems()) for i in tcp_packet['red'])
True
不隶属于 StackOverflow