AD Friend AD Friend - 1 month ago 8
Python Question

for loop with conditional strings

in my code i have for loop to a dict... and I get desired output as shown below..

dict = {"apple":5,"banana":3, "mangos":2}
columns = ('apple', 'banana','mangos')
for column in columns:
value = dict.get(column)
print column,value


Output:

apple 5
banana 3
mangos 2


But if my dict changes to

dict = {"apple":5,"Oranges":3, "mangos":2}


the same for loop would give me following output

columns = ('apple', 'banana','mangos')
for column in columns:
value = dict.get(column)
print column,value


I get following, which is expected

apple 5
banana None
mangos 2


Now the question is, is there a way I can set the coloum loop

columns = ('apple', 'banana','mangos')


so that the second value 'banana' could be either 'banana' or 'orange' ?

Answer
dict = {"apple":5,"oranges":3, "mangos":2}
columns = ('apple', 'banana' , 'oranges','mangos')
for column in columns:
    value = dict.get(column)
    if value:
        print(column,value)

Check if the value is there or not and then print it or OrderedDict, There's too many good answers, you could check if in the dict has 'oranges' or 'banana' and then change your columns based on what you find.

dict = {"apple":5,"oranges":3, "mangos":2}
if 'banana' in dict:  
    columns = ('apple', 'banana','mangos') 
else:
    columns = ('apple', 'oranges','mangos') 
for column in columns:
    value = dict.get(column)
    print(column,value)

Edited to use if 'banana' in dict because of Ev. Kounis's comment! Thanks.