2

辞書に文字列として格納されている整数キー がある場合、?を使用して複合フィールド名{'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']ます。)

4

3 に答える 3

3

str.format、たとえば「f-strings」とは異なり、完全なパーサーを使用しません。文法の関連するビットを引き出すには:

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
element_index     ::=  digit+ | index_string
index_string      ::=  <any source character except "]"> +

field_name角かっこで囲まれているのは、次のelement_indexいずれかです。

  1. 1つ以上の数字( -digit+のように、ただしすべてが0数字の場合のみ、これが2番目のケースに該当する理由)。また0start
  2. 「"]""以外の任意のソース文字のシーケンス。

したがって0['0']field_name"'0'"ではなく '0'、です。

...フォームの式は、'[index]'を使用してインデックスルックアップを実行し __getitem__()ます。

"'0' is {0['0']}".format(a_dict)置換はa_dict.__getitem__("'0'")であり、文法内で実際のを選択する方法はありませんa_dict['0']

于 2021-02-11T20:56:22.713 に答える
2

それはいけません。フォーマットするには、追加の引数を渡す必要があります。

>>> "'0' is {0[0]} {1}".format(a_dict, a_dict['0'])
于 2012-07-26T04:55:48.993 に答える
0

編集:私は問題を理解しました。dictを呼んでいます。期待どおりの「0」ではなく、文字列「'0'」のgetitem 。したがって、これは不可能です。ごめん。

于 2012-07-26T05:01:42.610 に答える