let's say you have a dictionary as follow:
{'A': (4, 1), 'C': (2, 0), 'B': (1, -1)}
How can you print it in the following format: each key and set of values in a new line without {} & ()
A 4 1
C 2 0
B 1 -1
how to add " " sign to the values, keep in mind values need to be integers.
This is what I have so far but can't figure out the " " part:
for k, v in sorted_league.items():
print(k, *v ,sep=' ')'
CodePudding user response:
This is not exactly what you want but may be acceptable. There is a
format string that reserves space for a sign:
D = {'A': (4, 1), 'C': (2, 0), 'B': (1, -1)}
for k,(a,b) in D.items():
print(f'{k} {a} {b: }')
Output:
A 4 1
C 2 0
B 1 -1
Otherwise, this works but is more complicated:
D = {'A': (4, 1), 'C': (2, 0), 'B': (1, -1)}
for k,(a,b) in D.items():
print(f'{k} {a} {" " if b>0 else ""}{b}')
Output:
A 4 1
C 2 0
B 1 -1
CodePudding user response:
You can use f-strings, which will get you what you want (assuming you want the sign of all items to be displayed):
sorted_league = {'A': (4, 1), 'C': (2, 0), 'B': (1, -1)}
for k, v in sorted_league.items():
print(k, f'{v[0]: }', f'{v[1]: }' ,sep=' ')
If you only want the sign of the second item in the tuple:
sorted_league = {'A': (4, 1), 'C': (2, 0), 'B': (1, -1)}
for k, v in sorted_league.items():
print(k, v[0], f'{v[1]: }' ,sep=' ')