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

Time:07-15

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']}

CodePudding user response:

Remove if after and

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

CodePudding user response:

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() != ''
}
  • Related