字符串格式 [str.format()] 带有一个字典键,它是一个数字的 str() [英] String formatting [str.format()] with a dictionary key which is a str() of a number
问题描述
这里是 Python 新手.我想知道是否有人可以帮助我在 str.format
.
Python neophyte here. I was wondering if someone could help with the KeyError
I am getting when using a dictionary for string interpolation in str.format
.
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
所以问题似乎在于将数字键解释为列表索引,恕我直言. 有没有办法解决这个问题?(即表示这是一个字典键)
So the problem seems to be in the interpretation of the numeric key as a list index, IMHO. Is there any way to work around this? (i.e. convey that this is instead a dictionary key)
TIA,如果之前有人问过这个问题,我深表歉意(找不到与我的搜索相关的任何内容).
TIA and apologies if this question has been asked before(couldn't find anything relevant with my search-fu).
编辑 1:键不是数字,正如之前错误地指出的那样.相反,它是一个数字的字符串表示 - 正如 BrenBarn 所指出的那样.
Edit 1: The key is not numeric as was erroneously noted, earlier. Instead it is a string representation of a number - as was pointed out by BrenBarn.
推荐答案
没有.根据文档:
因为 arg_name 不是引号分隔的,所以不能在格式字符串中指定任意的字典键(例如,字符串 '10' 或 ':-]').
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.
因此您不能使用由数字组成的字符串作为格式字符串中的字典键.
So you can't use strings consisting of numbers as dictionary keys in format strings.
请注意,您的键不是数字,并且不会尝试将其用作列表索引.您的密钥是一个恰好包含数字字符的字符串.它试图做的是使用数字 1(而不是字符串1")作为字典键.如果您使用数字 1 作为您的字典键(即,使您的 dict {'key1': 'val1', 1: 'val2'}
),它将起作用.
Note that your key isn't numeric, and it's not trying to use it as a list index. Your key is a string that happens to contain a digit character. What it's trying to do is use the number 1 (not the string "1") as a dictionary key. It will work if you use the number 1 as your dictionary key (i.e., make your dict {'key1': 'val1', 1: 'val2'}
).
这篇关于字符串格式 [str.format()] 带有一个字典键,它是一个数字的 str()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!