Search code examples
pythonkeyword-argumentjustify

Justify keys and values from a dict in PYTHON


I'm working on a program which will justify some keys and values from a dict called make_table.

This is what the body of my code should looks like:

def make_table(**kwargs):
    for key, value in kwargs.items():
        pass

make_table(
    key_position="right",
    value_position="center",
    song="Style",
    artist_name="Taylor $wift",
    album="1989"
)

And this is what I need to print as a result:

===================================
|             song |    Style     |
|      artist_name | Taylor $wift |
|            album |    1989      |
===================================

What I need to know now is how can I justify the content of my kwargs.items() like asked in the result and print them but WITHOUT printing the lines: key_position="right" and value_position="center" because their function is only to justify.

Thanks.


Solution

  • This function prints the table like what you asked but it changes the function signature to make things more simple. Also, it adapts to the length of your keys and values by looking at their respective longest length.

    def make_table(d, key_align, val_align):
        max_key_len = max(map(len, d.keys()))
        max_val_len = max(map(len, d.values()))
        
        n_equals = (2 + max_key_len + 3 + max_val_len + 2)
        s = n_equals * '=' + '\n'
        for key in d:
            s += "| "
            
            if key_align == 'left':
                s += "{key:<{length}}".format(key=key, length=max_key_len)
            elif key_align == 'right':
                s += "{key:>{length}}".format(key=key, length=max_key_len)
            elif key_align == 'center':
                s += "{key:^{length}}".format(key=key, length=max_key_len)
                
            s += " | "    
            
            if val_align == 'left':
                s += "{val:<{length}}".format(val=d[key], length=max_val_len)
            elif val_align == 'right':
                s += "{val:>{length}}".format(val=d[key], length=max_val_len)
            elif val_align == 'center':
                s += "{val:^{length}}".format(val=d[key], length=max_val_len)
                
            s += " |\n"
            
        s += n_equals * '='
                
                
        return s
    
    
    song_dict = {
        "Song": "Style",
        "Artist Name": "Taylor $wift",
        "Album": "1989"
    }
    
    table = make_table(song_dict, key_align='right', val_align='center')
    print(table)
    

    The output of the Python script:

    ==============================
    |        Song |    Style     |
    | Artist Name | Taylor $wift |
    |       Album |     1989     |
    ==============================