Python:将元组作为键的格式化字典

mmj*_*mmj 2 python format dictionary tuples

我想格式化一个字典进行打印(Python 2.7.3),字典有元组作为键.使用其他类型的键我可以做

>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W', 'altitude':100}
>>> 'Coordinates: {0[latitude]}, {0[longitude]}'.format(coord)
'Coordinates: 37.24N, -115.81W'
Run Code Online (Sandbox Code Playgroud)

我尝试了相同但它不适用于元组键.

>>> a={(1,1):1.453, (1,2):2.967}
>>> a[1,1]
1.453
>>> 'Values: {0[1,1]}'.format(a)

Traceback (most recent call last):
  File "<pyshell#66>", line 1, in <module>
    'Values: {0[1,1]}'.format(a)
KeyError: '1,1'
Run Code Online (Sandbox Code Playgroud)

为什么?如何在格式化字符串中引用元组键?

跟进

看来我们不能(见下面的答案).正如agf很快指出的那样,Python无法处理这个问题(希望它会被实现).与此同时,我设法通过以下解决方法引用格式字符串中的元组键:

my_tuple=(1,1)
b={str(x):a[x] for x in a} # converting tuple keys to string keys
('Values: {0[%s]}'%(str(my_tuple))).format(b) # using the tuple for formatting
Run Code Online (Sandbox Code Playgroud)

agf*_*agf 6

格式字符串语法下,field_name描述(强调我的):

field_name本身与开始arg_name要么是一个数或一个关键字.如果它是一个数字,它引用一个位置参数,如果它是一个关键字,它引用一个命名关键字参数.如果格式字符串中的数字arg_names按顺序为0,1,2,...,它们都可以省略(不仅仅是一些),数字0,1,2,...将按顺序自动插入.因为arg_name不是引号分隔的,所以不可能在格式字符串中指定任意字典键(例如,字符串'10'':-]').的arg_name后面可以任何数目的索引或属性表达式.表单的表达式'.name'选择使用的命名属性getattr(),而表单的表达式'[index]'使用索引查找__getitem__().

语法描述arg_name为:

arg_name          ::=  [identifier | integer]

在哪里identifier:

identifier ::=  (letter|"_") (letter | digit | "_")*

所以a tuple不是有效的arg_name,因为它既不是a identifier或an integer,也不能是任意字典键,因为不引用字符串键.

  • @mmj这真的归结为Python必须决定`1,1`是指`str`ing,'1,1'`还是`tuple`,`(1,1)`.它做的更简单,并假设它不是一个整数,它是一个字符串. (3认同)