1

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
  • 374
  • 1
  • 13

3 Answers3

3

Try join()

'This is output ' + ' '.join(f'{key}:{value}' for key, value in dic.items())
aksh02
  • 178
  • 1
  • 8
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())
blackraven
  • 5,284
  • 7
  • 19
  • 45
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
  • 1,145
  • 11
  • 26