If a dictionary has an integer key stored as a string {'0': 'foo'}
how would you reference that in Compound Field Names using .format()
?
I get that it may be un-pythonic (and bad programming) to have a dict with such keys...but in this case, it's also not possible to use this way:
>>> a_dict = {0: 'int zero',
... '0': 'string zero',
... '0start': 'starts with zero'}
>>> a_dict
{0: 'int zero', '0': 'string zero', '0start': 'starts with zero'}
>>> a_dict[0]
'int zero'
>>> a_dict['0']
'string zero'
>>> " 0 is {0[0]}".format(a_dict)
' 0 is int zero'
>>> "'0' is {0['0']}".format(a_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: "'0'"
>>> "'0start' is {0[0start]}".format(a_dict)
"'0start' is starts with zero"
{0[0]}.format(a_dict)
will always refer to the key int 0
even if there isn't one, so at least that's consistent:
>>> del a_dict[0]
>>> a_dict
{'0': 'string zero', '0start': 'starts with zero'}
>>> "{0[0]}".format(a_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 0L
(And yes, I know I could just do '%s' % a_dict['0']
if required.)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…