# hash map – Python – improve function to create a table from a dictionary

Ramen enthusiast here: First, I want to say thank you! I’m currently learning Python for a masters and am trying to improve the best I can, as I’ll need to know how to code in my future career. Without having any programming experience prior, honestly, searching questions on this community cite has helped way more than any textbook could, so thank you!

So here’s my question! I currently have a function that builds a table from a dictionary, no matter how long the characters of either the keys or values are.

However, I’m trying to get better and I’m sure there’s a more “Pythonic” way to write this (i.e. a more simple way). This is just what I was able to come to with my limited knowledge. If anyone wouldn’t mind taking the time to write what they would do instead, and (most importantly) explain why, I would be so grateful! Also, please feel free to share any resources that you have found helpful while you learned how to code in Python and/or R!

def salaryTable(itemsDict):

lengthRight=max( ( len(k) for k,v in itemsDict.items() ) )
lengthLeft=max( ( len(str(v)) for k,v in itemsDict.items() ) )

print( "Major".ljust(lengthRight+7) + "Salary".rjust(lengthLeft+7) )
print( '-' * (lengthRight+lengthLeft+14) )

for k,v in itemsDict.items():
print( k.ljust(lengthRight+7,'.') + str(v).rjust(lengthLeft+7) )

And here’s the two dictionaries I used to test both left and right:

# what it produces when keys or values in the dictionary are longer than the parameter's # leftWidth and rightWidth

majors={'English Composition':45000,
'Mechanical Engineering with a concentration in Maritime Mechanics':75000,
'Applied Math with a concentration in Computer Science':80000}

# testing on a dictionary with a long value

majors2={'English Composition':45000,
'Mechanical Engineering':75000,
'Applied Math':"\$100,000 thousand dollars per year USD"}