Search code examples
python-3.xdictionarydictionary-comprehension

how to do dict comprehension for multiple for and if loops in python?


i have a code like below:

out={}
for each_val in values["data"]['values']:
    if each_val['value'].strip() != '':
       if 'frequency' in each_val:
           out[each_val['value']] = each_val['frequency']
       else:
           out[each_val['value']] = None

i am trying to make it one line with dict comprehension but not able to do it with 2 if loops inside for loop. Below is the code I tried but getting warnings and errors

out = {each_val['value']: each_val['frequency'] if 'frequency' in each_val and if each_val['value'].strip() != '' else None for each_val in values["data"]['values']}

Solution

  • You should put the filter as an if clause in the comprehension. Also, use the dict.get method to default the value to None when a key is not found in the dict:

    out = {
        each_val['value']: each_val.get('frequency')
        for each_val in values["data"]['values']
        if each_val['value'].strip() != ''
    }