user4516038
user4516038

Reputation:

Print a dictionary without brackets and parenthesis

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=' ')'

Upvotes: 0

Views: 1672

Answers (2)

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=' ')

Upvotes: 0

Mark Tolonen
Mark Tolonen

Reputation: 177705

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

Upvotes: 1

Related Questions