Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pythonic way to print data this data with headers

I have this dataset:

[('Stuff', '  ')
('Available in several colors.', '  ')
('A fits B by Sometimes.', '  ')
('handle      $148', 'A ')
('handle base  $23', 'A ')
('mirror base      $24', 'A ')
(' handle      $31', 'B ')
('handle base,     $23', 'B ')
('Mirror      $24', 'B ')
]

What I need to do is print this data with a "header" based off the second item in the list. Only printing the header when it changes. In this sample, the only 3 options are " ", "A ", and "B ". But in my actual data set there could be 100+ different options, so hard coding them in is not really an options.

I want the printed data to look like this (skipping the " ")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Stuff.
Available in several colors.
A fits B by Sometimes.
A ----------------------
handle      $148
handle base  $23
mirror base      $24
B ----------------------
 handle      $31
handle base,     $23
Mirror      $24

the only way to do this I can think of is to hard code the values in, but with 100+ possibilities this would take forever. There must be a better way.

a_printed = False
b_printed = False
for item in list1:
    if item[1] == '  ':
        print(item[0])
    elif item[1] == 'A ':
        if a_printed != True:
            print('A --------------')
        a_printed = True
        print(item[0])
    elif item[1] == 'B ':
        if b_printed != True:
            print('B --------------')
        b_printed = True
        print(item[0])

Any help is appreciated.

>Solution :

You don’t need to hard-code the header values, just set a variable to the header and test if the new header is different.

last_header = '  '
for value, header in list1:
    if header != last_header:
        print(header, '--------------')
        last_header = header
    print value
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading