dic2={(0,0):'⬃',(-2,-2):'⇩',(-2,-3):'⇩'}
I would like to print the dictionary's values and they can be shown as the position I have allocated. How I can print that?
dic2={(0,0):'⬃',(-2,-2):'⇩',(-2,-3):'⇩'}
I would like to print the dictionary's values and they can be shown as the position I have allocated. How I can print that?
My understanding is that you want to print your values on a grid at the coordinates specified by the key.
Let's assume a square matrix of size N
. I will show empty cells as ⋅
for clarity.
You can use:
N = 5
dic2={(0,0):'⬃',(-2,-2):'⇩',(-2,-3):'⇩'}
matrix = [['⋅' for _ in range(5)] for _ in range(5)]
for (x,y), v in dic2.items():
matrix[x][y] = v
print('\n'.join(map(''.join, matrix)))
Alternatively, you wan rework the dictionary and use:
N = 5
dic3 = {(i if i>=0 else N+i, j if j>=0 else N+j):v for (i,j),v in dic2.items()}
# {(0, 0): '⬃', (3, 3): '⇩', (3, 2): '⇩'}
print('\n'.join([''.join([dic3.get((i, j), '⋅')
for i in range(N)]) for j in range(N)]))
Output:
⬃⋅⋅⋅⋅
⋅⋅⋅⋅⋅
⋅⋅⋅⋅⋅
⋅⋅⇩⇩⋅
⋅⋅⋅⋅⋅
If you must print them, below is a version of the first suggestion in mozway's answer, where you initiate a matrix full of a single character and then fill it at certain indices [that correspond to the coordinates] according to dic2
.
bgChar = '+' # '▪' # '●' # ' ' # '⁜' # set a "background" character
dic2 = {(0,0):'⬃', (-2,-2):'⇩', (-2,-3):'⇩'}
getRange = lambda l: (min(l), max(l))
x_min, x_max = getRange([c[0] for c in dic2])
y_min, y_max = getRange([c[1] for c in dic2])
myCanvas = [[f'{bgChar:^3}']*(x_max-x_min+3) for _ in range(y_max-y_min+3)]
for (x,y),v in dic2.items():
myCanvas[y+1-y_min][x+1-x_min] = f'{v:^3}'
print(' '*3+''.join([f'{i+1+x_min:^3}' for i in range(x_max - x_min + 3)]))
for i, r in list(enumerate(myCanvas))[::-1]:
print(''.join([f'{i-1+y_min:^3}']+r))
I added the numbers for the axes and also changed the character (bgChar
) in "coordinates" that are not covered in dic2
(because I felt like using space ' '
made it a bit hard to figure out the coordinates of printed arrows).
However, as you can see, variations in character width mess up the alignment of x-coordinates, so it might be better to plot rather than print, using something like matplotlib.pyplot
which has a handy method called annotate
.
import matplotlib.pyplot as plt
dic2={(0,0):'⬃',(-2,-2):'⇩',(-2,-3):'⇩'}
getRange = lambda l: (min(l), max(l))
x_min, x_max = getRange([c[0] for c in dic2])
y_min, y_max = getRange([c[1] for c in dic2])
fig, myCanvas = plt.subplots()
myCanvas.set_xlim(x_min-1, x_max+1)
myCanvas.set_ylim(y_min-1, y_max+1)
for xy, v in dic2.items(): myCanvas.annotate(v, xy, xy)
plt.show()