[Python] Format String based on List of Dictionaries

Discussão em 'Python' iniciado por Stack, Abril 10, 2025.

  1. Stack

    Stack Membro Participativo

    I have string which needs to be substituted with values from a list of dictionaries. The size of the list can vary. Based on the size of the list, the string will be repeated because accordingly the data from the list will be substituted.

    e.g. string is like

    str_template = '''
    Part 1: {}
    Part 2:
    {}'''


    Let's say the input list is:

    l2 = [{'Val1': "c", 'Val2': "d"},{'Val1': "e", 'Val2': "f"}]


    l2 is the input.


    def repeating(template, n):
    return '\n\n'.join([template] * n)

    def test_formatting(listval):
    size = len(listval)
    final_template = (repeating(str_template,size))
    # This would print
    print(final_template)


    Part 1: {}
    Part 2:
    {}

    Part 1: {}
    Part 2:
    {}


    Hence, there are 4 places to be substituted. How to go through the list of dictionaries dynamically and substitute that?

    I am sure that would be a possible one liner which I am missing.

    Continue reading...

Compartilhe esta Página