Home > Enterprise >  how to transform a loop for with if condition into comprehension dictionary
how to transform a loop for with if condition into comprehension dictionary

Time:11-11

I'm not at ease with comprehension dictionaries I would like to transform this loop into a dictionary comprehension.

Thanks for your help

dico={}
for key in ['good','very good','bad','very bad','not good not bad']:
  if key in['good','very good']:
    dico[key]='green'
  else:
    dico[key]='red'
print(dico)

Here is what's expected

{'good': 'green',
 'very good': 'green',
 'bad': 'red',
 'very bad': 'red',
 'not good not bad': 'red'}

CodePudding user response:

I think you you're looking to this

dico = {key: ['red', 'green'] [key in ['good','very good']] for key in ['good','very good','bad','very bad','not good not bad']}

CodePudding user response:

Try this syntax

{k:'green' if k in ['good','very good'] else 'red' for k in ['good','very good','bad','very bad','not good not bad']}
  • Related