Buda Gavril
Buda Gavril

Reputation: 21657

new style formating in python with dictionaries

I'm learning python and I don't understand something about the 'new style' of formatting. Here is my code:

>>> d={'n':32,'f':5.03,'s':'test string'}
>>> '{0[n]} {0[f]} {0[s]} {1}'.format(d, 'other')
'32 5.03 test string other'

but when I type in the console:

>>> d[n]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
>>> d['n']
32

So why in the formatted string, 0[n] without quotes was able to read from the dictionary the value with the key 'n' (in this case the key is a string) but when I've tried this in the console, it didn't worked.

Also, what would happen if the key is not a string?

Thanks

Upvotes: 0

Views: 51

Answers (1)

DYZ
DYZ

Reputation: 57033

'{0[n]}...' is a string that is interpreted by the method format(). The Python parser does not care about the content of that string, and format can use any notation, regardless of what is valid in Python and what is not.

O[n] is not a string, it is a Python expression. When Python parses it, it attempts to resolve n as a variable, which, in your case, does not exist. Your attempt would work if you executed n='n' before the lookup.

Upvotes: 1

Related Questions