Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

python 2.7 - String formatting [str.format()] with a dictionary key which is a str() of a number

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

The above works fine and yields:

Interpolating val1

However doing the following:

dictionary = {'key1': 'val1', '1': 'val2'}

string2 = 'Interpolating {0[1]}'.format(dictionary)
print string2

results in:

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 and apologies if this question has been asked before(couldn't find anything relevant with my search-fu).

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No. According to 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.

So you can't use strings consisting of numbers as dictionary keys in format strings.

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'}).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...