Search code examples
python-3.xdictionaryf-string

String format for dictionary with f-strings


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.


Solution

  • 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())