mark86v1
mark86v1

Reputation: 312

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

Upvotes: 1

Views: 495

Answers (2)

iamjaydev
iamjaydev

Reputation: 140

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

Upvotes: 2

blhsing
blhsing

Reputation: 106445

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

Upvotes: 1

Related Questions