2
\$\begingroup\$

Is there a shorter way of taking a dict with varying length lists and printing it to screen? Shortcomings of this method also include that values which aren't lists are printed as letters separated by spaces, and values which are numbers produce an error. Would it be better to write a class which could accept any type of dict value, or is it best to have different classes for different types of dict?

class PrintDict(object):
    """prints dict keys and values including lists
    except if values are numbers"""

    def print_dict_to_screen(self, data):

        self.data = data
        print ""
        for key in sorted(self.data):
            print "\n\n%s" % str(key)
            items = len(self.data[key])
            iterate = -1
            for i in range(items):
                iterate += 1
                print self.data[key][iterate],

crops = {'trees' : ['hazelnut'], 
'potatoes': ['early', 'main'], 
'legumes': ['broad beans', 'peas', 'runner beans'], 
'brassicas': ['cabbages', 'sprouts', 'kale', 'swede', 'turnip'], 
'onions and roots': ['carrots',   'parsnips', 
'beetroot', 'onions', 'shallots'], 
'other': ['lettuce', 'sweet corn', 'flowers'],
'fruit': ['blackberry', 'blackcurrant', 'raspberry']}

print_ = PrintDict()

print_.print_dict_to_screen(crops) 
\$\endgroup\$
3
\$\begingroup\$

I don't see any reason why the PrintDict class should exist. Furthermore, there's no point in keeping self.data as part of the object state. A standalone function print_dict_to_screen(data) would work just fine.

Much of the code is concerned with printing out the value lists in the right format. This whole chunk of code…

items = len(self.data[key])
iterate = -1
for i in range(items):
    iterate += 1
    print self.data[key][iterate],

… could be replaced with

print ' '.join(self.data[key])

It's usually more manageable if you consistently put your newlines at the end rather than at the beginning of your output.

There's no need to cast the key as a str, since the %s format specification always interprets its input as a string.

So, the code can be simplified to:

def print_dict_to_screen(self, data):
    for key in sorted(data):
        print "%s\n%s\n" % (key, ' '.join(data[key]))

It would be even cleaner if the output had no excessive leading or trailing newlines. To accomplish that, I would use join() again:

def dict_to_string(data):
    return "\n\n".join(
        "%s\n%s" % (key, ' '.join(data[key])) for key in sorted(data)
    )

Here, dict_to_string() returns the string to be printed rather than printing it directly. Then, the caller is free to print the resulting string, log it to a file, or whatever.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.