I have the following style of data i.e. a list of strings:
fruits_lst = ['Apple:Good','Banana:Off','Orange:Excellent','Blueberry:Excellent','Raspberry:Good']
I am looking to achieve this result, via comprehension in a single line of code:
{'APPLE:GOOD': 'Ripe',
'BLUEBERRY:EXCELLENT': 'Ripe',
'Banana:Off': 'Off',
'ORANGE:EXCELLENT': 'Ripe',
'RASPBERRY:GOOD': 'Ripe'}
This result has been achieved by deploying the following loop method:
fruits_dict = {}
for fruit in fruits_lst:
if fruit.split(':')[1] != 'Off':
fruits_dict[fruit.upper()] = 'Ripe'
else:
fruits_dict[fruit.lower()] = 'Off'
So this creates a dictionary, but also needs to perform a different function to produce the desired key depending on the fruit.split(':')[1] value.
I have been attempting to re-write this so as to achieve the same result via a comprehension in one line of code, but am still trying to figure out the syntax to deploy to achieve this result.
I have attempted:
{fruit.upper():'Ripe' for fruit in fruits_lst if fruit.split(':') != 'Off' else fruit.lower():'Off'}
{fruit.upper():'Ripe' if fruit.split(':') != 'Off' else fruit.lower():'Off' for fruit in fruits_lst}
however, these all return a SyntaxError.
I note that this produces the dictionary of ripe fruits, but then I am obviously missing the off fruits:
{fruit.upper():'Ripe' for fruit in fruits_lst if fruit.split(':') != 'Off'}
{'APPLE:GOOD': 'Ripe',
'BANANA:OFF': 'Ripe',
'BLUEBERRY:EXCELLENT': 'Ripe',
'ORANGE:EXCELLENT': 'Ripe',
'RASPBERRY:GOOD': 'Ripe'}
I am looking for the right syntax here, but further to better understand what it is I am missing in how the generation of a dictionary via a comprehension method with an if else condition should be written in this instance.
Thanks!
The question is now updated with more specific detail. Thank you!
CodePudding user response:
One option is to use OR
in a generator expression and use the dict constructor:
out = dict((fruit.upper(),'Ripe') * (fruit.split(':')[1]!='Off') or (fruit,'Off') for fruit in fruits_lst)
or simply implement the if-else in a generator expression and construct the dict:
out = dict((fruit.upper(),'Ripe') if fruit.split(':')[1]!='Off' else (fruit,'Off') for fruit in fruits_lst)
Output:
{'APPLE:GOOD': 'Ripe',
'Banana:Off': 'Off',
'ORANGE:EXCELLENT': 'Ripe',
'BLUEBERRY:EXCELLENT': 'Ripe',
'RASPBERRY:GOOD': 'Ripe'}
CodePudding user response:
Another version:
out = {
fruit: "Off" if fruit.split(":")[1] == "Off" else "Ripe"
for fruit in fruits_lst
}
print(out)
Prints:
{
"Apple:Good": "Ripe",
"Banana:Off": "Off",
"Orange:Excellent": "Ripe",
"Blueberry:Excellent": "Ripe",
"Raspberry:Good": "Ripe",
}
Or shorter:
out = {
fruit: "Off" if fruit.endswith(":Off") else "Ripe" for fruit in fruits_lst
}