辞書に文字列として格納されている整数キー がある場合、?を使用して複合フィールド名{'0': 'foo'}
でそれをどのように参照しますか?.format()
私はそのようなキーでdictを持っていることは非pythonic (そして悪いプログラミング)かもしれないと思います...しかしこの場合、このように使うこともできません:
>>> 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)
キーがない場合でも常にキーを参照するint 0
ため、少なくとも一貫性があります。
>>> 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
(そして、はい、私は必要に応じて私ができることを知ってい'%s' % a_dict['0']
ます。)