0

Python 3 - I am using a for loop to print values from a dictionary. Some dictionaries within rawData have "RecurringCharges" as an empty list. I am checking to see if the list is empty and either populating with "0.0" if empty or the "Amount" if populated.

Creating the IF statement in my For Loop presents a new print statement and prints to a new line. I would like it to be one continuous line.

for each in rawData['ReservedInstancesOfferings']:
    print('PDX', ','
          , each['InstanceType'], ','
          , each['InstanceTenancy'], ','
          , each['ProductDescription'], ','
          , each['OfferingType'], ','
          , each['Duration'], ','
          , each['ReservedInstancesOfferingId'], ','
          , each['FixedPrice'], ',',
          )
    if not each['RecurringCharges']:
        print("0.0")
    else:
        print(each['RecurringCharges'][0].get('Amount'))
Ka_Fari
  • 5
  • 4
  • why don't you just do the check in RecurringCharges before the first print, and then include the result in a single print statement? – SuperStew Dec 15 '17 at 20:51

4 Answers4

2

If using Python 3, add to the end of each print statement a comma and then end="", such as:

 print(each['RecurringCharges'][0].get('Amount'), end="")
NFB
  • 642
  • 8
  • 26
0

I found the answer shortly after posting: include the parameter end='' in the first print statement.

for each in rawData['ReservedInstancesOfferings']:
    print('PDX', ','
          , each['InstanceType'], ','
          , each['InstanceTenancy'], ','
          , each['ProductDescription'], ','
          , each['OfferingType'], ','
          , each['Duration'], ','
          , each['ReservedInstancesOfferingId'], ','
          , each['FixedPrice'], ',', end=''
          )
    if not each['RecurringCharges']:
        print("0.0")
    else:
        print(each['RecurringCharges'][0].get('Amount'))
Ka_Fari
  • 5
  • 4
0

Instead of using the print function, use stdout!

import sys
sys.stdout.write('this is on a line ')
sys.stdout.write('and this is on that same line!')

With sys.stdout.write(), if you want a newline, you put \n in the string, otherwise, it's on the same line.

Qwerty
  • 1,252
  • 1
  • 11
  • 23
0

Of course you could just follow How to print without newline or space?

but in that case, it would be better to insert your expression as the last argument in a ternary expression:

      , each['ReservedInstancesOfferingId'], ','
      , each['FixedPrice'], ','
      , "0.0" if not each['RecurringCharges'] else each['RecurringCharges'][0].get('Amount')
      )
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219