+-
![python-2.7 – 使用字典键格式化[str.format()],字典键是数字的str() python-2.7 – 使用字典键格式化[str.format()],字典键是数字的str()](/img/no_img.png)
Python新手在这里.我想知道是否有人可以帮助我在
str.format中使用字典进行字符串插值时得到的KeyError.
dictionary = {'key1': 'val1', '1': 'val2'}
string1 = 'Interpolating {0[key1]}'.format(dictionary)
print string1
以上工作正常,产量:
Interpolating val1
但是请执行以下操作:
dictionary = {'key1': 'val1', '1': 'val2'}
string2 = 'Interpolating {0[1]}'.format(dictionary)
print string2
结果是:
Traceback (most recent call last):
File "test.py", line 3, in <module>
string2 = 'Interpolating {0[1]}'.format(dictionary)
KeyError: 1L
所以问题似乎在于将数字键解释为列表索引,恕我直言.有什么方法可以解决这个问题吗? (即传达这是一个字典键)
如果之前已经问过这个问题,TIA并道歉(找不到与我的搜索相关的任何内容).
编辑1:密钥不是数字,正如之前错误记录的那样.相反,它是一个数字的字符串表示 – 正如BrenBarn所指出的那样.
最佳答案
不.根据 the documentation:
Because arg_name is not quote-delimited, it is not possible to specify arbitrary dictionary keys (e.g., the strings ’10’ or ‘:-]’) within a format string.
因此,您不能在格式字符串中使用由数字组成的字符串作为字典键.
请注意,您的密钥不是数字,并且它不会尝试将其用作列表索引.您的密钥是一个恰好包含数字字符的字符串.它尝试做的是使用数字1(不是字符串“1”)作为字典键.如果您使用数字1作为词典键(即,使您的词典{‘key1’:’val1′,1:’val2’}),它将起作用.
点击查看更多相关文章
转载注明原文:python-2.7 – 使用字典键格式化[str.format()],字典键是数字的str() - 乐贴网