python - 使用字典和复合字段 format() 并将整数键存储为字符串

标签 python string dictionary

如果字典有一个存储为字符串的整数键 {'0': 'foo'} 您将如何在 Compound Field Names 中引用它使用 .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']。)

最佳答案

str.format,不同于例如"f-strings" ,不使用完整的解析器。拉出 grammar 的相关位:

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. 一个或多个数字(digit+,如0 - 但前提是它们都是所有数字,这就是为什么0start 属于第二种情况);或
  2. 一系列 “除“]”之外的任何源字符

因此对于 0['0'] field_name"'0'"不是 '0'

... an expression of the form '[index]' does an index lookup using __getitem__().

对于 "'0' is {0['0']}".format(a_dict) 替换为 a_dict.__getitem__("'0'") ,并且在语法中无法选择实际的 a_dict['0']

关于python - 使用字典和复合字段 format() 并将整数键存储为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66162386/

相关文章:

string - Powershell字符串分割差异

python - 当你调用 `if key in dict` 时会发生什么

python - 计算候选人被投票的次数

python - 将带有俄语字符的 numpy.ndarray 写入文件

ruby - 如何将字符串拆分为多个单词的数组?

c - 这是分配内存的正确方法吗?

ios - swift 错误 : Reference to generic type Dictionary requires arguments in <. ..>

Python:使用 OpenCV 进行字母修复以进行文本识别

python - INSERT 上的 SQL 语法错误

python - 使用计数和百分比创建列联表 Pandas