zeako
zeako

Reputation: 148

Python printing Formatted text with lists nested in dict

I'm in the process of writing a script that will output some system info to a text file, I've got all the info I need but I stumbled upon one problem,

This is a part of the dict:

machine_info = {
    ...
    'processors': get_processors(),
    ...  
}

the get_processors() returns a list of all the machine's processors,

now for the problem - I want to print the processor(s) data, my printing template for now is:

print """...
Processor(s):\t%(processors)s
...""" % machine_info

obviously it doesn't really work, it prints the whole list, and I want to print it formatted,
in a way that will look like this:

...
Processor(s):   processor_1_info
                processor_2_info
                ...
...

How can I manage to do such thing? is there a better way to format the text than using \t so it'll be more flexible? also, is there a better way to print out the info? considering in the end it will output to a text file,

Thanks.

Upvotes: 3

Views: 100

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250871

Something like this:

processors_info = "\n\t\t\t".join(machine_info['processors'])
print "Processor(s):\t{}".format(processors_info)

Demo:

>>> info = ['processor_1_info', 'processor_2_info']
>>> processors_info = "\n\t\t\t".join(info)
>>> print "Processor(s):\t{}".format(processors_info)
Processor(s):   processor_1_info
                processor_2_info

Another way using string formatting:

info = ['processor_1_info', 'processor_2_info', 'processor_3_info']
#info = machine_info['processors'] for your code.
print "Processor(s):{:>20s}".format(info[0])
for item in info[1:]:
    print "{:>33s}".format(item)

output:

Processor(s):    processor_1_info
                 processor_2_info
                 processor_3_info

Upvotes: 3

Related Questions