Home > Mobile >  Python3, search for a value in a dict
Python3, search for a value in a dict

Time:03-22

I have this dict variable:

result = {'result': [{'code': 'switch', 'value': False}, {'code': 'battery_percentage', 'value': 100}, {'code': 'time_use', 'value': 4370}, {'code': 'weather_delay', 'value': 'cancel'}, {'code': 'countdown', 'value': 563}, {'code': 'work_state', 'value': 'idle'}, {'code': 'smart_weather', 'value': 'sunny'}, {'code': 'use_time_one', 'value': 602}], 'success': True, 't': 1647114301811, 'tid': '521dc986a3654ecaff3b6da7a08cf3a'}

I just need to search for the value of the first 'switch', but apparently all my tests went wrong.

How can I get the boolean value of the "switch"?

CodePudding user response:

If you want to stop the search at the first valid entry, you could use next and a generator expression:

next(d.get('value') for d in result['result'] if d.get('code')=='switch')

Output:

False
  • Related