Printing a pattern through the use of a dictionary

We had to port a program from c to python. The code works but uses a dictionary to solve the problem. This doesn't feel like the right use of a dictionary. Is there a better way?

#!/usr/bin/env python3

def main():
while True:
height = input("Height: ")
try:
height = int(height)
if height >= 0:
break
except:
pass

mtn={}
space_mtn(height,mtn)
hashs_mtn(height,mtn)
print_mtn(height,mtn)

def space_mtn(height,mtn):

for i in range(height):
for j in range(2*height+2):
mtn[i,j]=" "
return

def hashs_mtn(height,mtn):

for i in range(height):
for  j in range(height-1,height-i-2,-1):
mtn[i,j] = '#'

for i in range(height):
for j in range(height+2,height+i+3):
mtn[i,j] = '#'
return

def print_mtn(height,mtn):

for i in range(height):
for j in range(height+3+i):
print("{}".format(mtn[i,j]),end="")
print("")
return

if __name__ == "__main__":
main()


For how you're using it, it seems like a list of lists would make more sense than a dict. This is somewhat like a 2-dimensional array in C.

Your mtn initialization becomes:

mtn = []


You'll need to do a little more work in space_mtn to generate the sublists:

def space_mtn(height,mtn):
for i in range(height):
mtn.append([])             # Append an empty sublist at each level
for j in range(2*height+2):
mtn[-1].append(" ")    # Append a space to the end of the currently-last list
return


Now in hash_mtn and print_mtn, just change your mtn[i,j] calls to mtn[i][j].

Now, there are lots of ways to make this code less C-like and more idiomatic python, or "Pythonic". I'll just say that it's possible (although not necessarily "best") to get equivalent functionality by replacing everything after your input while loop with one line:

print('\n'.join('{0:>{1}}  {0:{1}}'.format('#'*(i+1), height) for i in range(height)))

• thanks. when you mtn[-1].append(" ") are you placing a space inside of the last mtn([])?
– DCR
Commented Feb 9, 2017 at 21:12
• @DCR Yes, mtn[-1] means "the last item in mtn".
– glibdud
Commented Feb 9, 2017 at 21:12
• I got that I just wanted to make sure I understood. You're creating a list item and then placing a space in that list
– DCR
Commented Feb 9, 2017 at 21:13

Dictionaries are great. As long as you don't care about a specific order (though there are ways of making them ordered and I believe they will be in a upcoming release of python).

In your case maybe the use of zip could be useful.

• Dictionaries being ordered is also considered an implementation detail. If you need an ordered mapping use OrderedDict to always be safe.
– Jim Fasarakis-Hilliard
Commented Feb 9, 2017 at 20:04