0

I am reading the Python documentation on fancier output formatting and they have example code which is confusing. In the following code:

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}

print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table))

Jack: 4098; Sjoerd: 4127; Dcab: 8637678

What does the 0 refer to in {0[Jack]:d} and {0[Sjoerd]:d}. The tutorial's explanation omits any hint about the function of those zeros. This video tutorial about formatting strings uses the same syntax without explaining it clearly too!

If I put a 1 in the place of 0 I get the error:

IndexError: tuple index out of range

What on Earth has the tuple have to do with it?

Taken from the Documentation:

If you have a really long format string that you don’t want to split up, it would be nice if you could reference the variables to be formatted by name instead of by position. This can be done by simply passing the dict and using square brackets '[]' to access the keys

2
  • 1
    0 refers to the first argument of format, i.e. table. Commented Apr 3, 2019 at 20:07
  • 1
    Please don't edit answers into your question. That's what the answer section is for. =) Commented Apr 3, 2019 at 22:03

2 Answers 2

3

You can just use:

table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {Jack}; Sjoerd: {Sjoerd}; Dcab: {Dcab}'.format(**table))
Sign up to request clarification or add additional context in comments.

1 Comment

Yes indeed this is the way of choosing the keyword to extract the value from the dictionary. Many thanks for ur contribution.
2

The 0 is the index of the format argument, i.e. table in this case.

It doesn't work with 1 because there's only one argument, that's what "tuple index out of range" is saying.

The documentation does mention this here:

A number in the brackets can be used to refer to the position of the object passed into the str.format() method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.