0

I have a dictionary and I want to print the key and values of this in f-strings format.

Sample 1:

dic = {'A': 1, 'B': 2}
Output: "This is output A:1 B:2"

Sample 2:

dic = {'A': 1, 'B': 2, 'C': 3}
Output: "This is output A:1 B:2 C:3"

I would like to request a general answer so that I could add more key-value pairs.

Trong Van
  • 354
  • 1
  • 12

3 Answers3

2

You could iterate through the key-value pairs, and print the output accordingly:

dic = {'A': 1, 'B': 2, 'C': 3}
print('This is output', end=' ')
for k,v in dic.items():
    print(str(k) + ':' + str(v), end=' ')

Output

This is output A:1 B:2 C:3 

Alternatively you could concatenate the string (same output):

dic = {'A': 1, 'B': 2, 'C': 3}
s = ''
for k,v in dic.items():
    s += f'{k}:{v} '   #thanks to @blueteeth
print('This is output', s.strip())
Black Raven
  • 2,351
  • 1
  • 9
  • 28
1

Try join()

'This is output ' + ' '.join(f'{key}:{value}' for key, value in dic.items())
aksh02
  • 118
  • 7
1

This is what you need -

d = {"A": 1, "B": 2, "C": 3}
print("This is output ")
for key, value in d.items():
    print(f"{key}:{value}", end=" ")
Amit Pathak
  • 771
  • 5
  • 18