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

前端 未结 4 1916
难免孤独
难免孤独 2020-12-02 01:24

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.

相关标签:
4条回答
  • 2020-12-02 02:09

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

    0 讨论(0)
  • 2020-12-02 02:14

    If your dictionary keys are strings, a possible workaround is to convert your dictionary to a class:

    class ClassFromDict:
        def __init__ (self, dct) :
            for key in dct.keys():
                self.__dict__[key] = dct[key]
    
    dictionary = {'key1': 'val1', '1': 'val2'}
    classfromdict = ClassFromDict(dictionary)
    
    string1 = 'Interpolating {0.key1}'.format(classfromdict)
    print string1
    string2 = 'Interpolating {0.1}'.format(classfromdict)
    print string2
    
    0 讨论(0)
  • 2020-12-02 02:16

    I think what you are looking for is:

    dictionary = {'key1': 'val1', '1': 'val2'}
    string2 = 'Interpolating {key1}'.format(**dictionary)
    print string2
    
    0 讨论(0)
  • 2020-12-02 02:17

    You're right - the parser isn't that complex, and can't handle variable subscripts for dictionaries. Your work around is:

    string2 = 'Interpolating {somevar}'.format(whateverhere..., somevar=dictionary['1'])
    
    0 讨论(0)
提交回复
热议问题