2

I want to format a dictionary for printing (Python 2.7.3), and the dictionary has tuples as keys. With other types of keys I can do

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

I tried the same but it does not work with tuple keys.

>>> 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'

Why? How I can refer to tuple keys in formatting string?

FOLLOW UP

It seems we can't (see answer below). As agf quickly pointed out, Python can't handle this (hope it will be implemented). In the meantime, I managed to refer to tuple keys in format string with the following workaround:

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
4

1 回答 1

6

Format String Syntax下,field_name描述(强调我的):

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

语法描述arg_name为:

arg_name ::= [标识符 | 整数]

哪里identifier是:

标识符 ::= (字母|"_") (字母 | 数字 | "_")*

因此 atuple不是有效arg_name的,因为它既不是 an 也不是identifieran integer,并且不能是任意字典键,因为没有引用字符串键。

于 2012-04-10T22:18:08.373 回答