Search code examples
pythonstringdictionaryformattingstring-formatting

Format a string using dictionary unpacking (Python 3.9)


mystr = '{1} {0}'
mydict = {'0': '5', '1': 'ZIDANE'}
result = mystr.format(**mydict)

Which raises:

IndexError: Replacement index 1 out of range for positional args tuple

I can do the following:

mystr = '{name} {number}'
mydict = {'number': '5', 'name': 'ZIDANE'}
result = mystr.format(**mydict)

This gives me the result: ZIDANE 5

How can I achieve the same for:

mystr = '{1} {0}'
mydict = {'0': '5', '1': 'ZIDANE'}

Solution

  • The problem is that the keys are (string) of integer and this is in conflict with the notation for a substitution with list (2nd example). This is due (I guess) by the implementation of __getitem__, here some more examples.

    Here with non-integer keys:

    mydict = {'0.': '5', '1.': 'ZIDANE'}  # with float-keys it works
    print('{d[0.]} {d[1.]}'.format(d=mydict))
    

    Here an example with a list

    mylst = ['5', 'ZIDANE']
    print('{l[0]} {l[1]}'.format(l=mylst))
    

    A similar side-effect is encountered with dictionaries:

    print(dict(a=5, b='ZIDANE'))
    #{'a': 5, 'b': 'ZIDANE'}
    print(dict(1=5, 2='ZIDANE'))
    #SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
    print(dict('1'=5, '2'='ZIDANE'))
    #SyntaxError: expression cannot contain assignment, perhaps you meant "=="?