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

前端 未结 4 1926
难免孤独
难免孤独 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: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
    

提交回复
热议问题