如果字典有一个整数键存储为字符串 {'0': 'foo'}
,您将如何在复合字段名称中使用.format()
?
我知道拥有这样的键的字典可能是非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']
如果需要我可以这样做。)