Search code examples
pythonpython-3.xdictionarykeyerror

KeyError in dict but Key exists


I am working on parsing a dict of dicts which look likes this:

data = {0: {},
        1: {'1': 'M_AVL_002'},
        2: {'2': 'CloudServiceAvailability'},
        3: {'3': 'P_001'},
        4: {'4': '2.592 x10^6'},
        5: {'4': 'second'},
        6: {'3': 'E_001'},
        7: {'4': ' 100 x (P_001- M_TQD_001)/P_001'},
        8: {'4': 'ISO80000'},
        9: {'4': 'percentage'},
        10: {'1': 'M_TQD_001'},
        11: {'2': 'TotalQualifiedDowntime'},
        12: {'3': 'E_001'},
        13: {'4': '?(M_QDT_001)'},
        14: {'4': 'ISO80000'},
        15: {'4': 'second'}}

I want to access some values like this:

for metric in XML.findall("{http://standards.iso.org/iso-iec/19086/-2/ed-1/en}Metric"):
        for row,value in data.items() :
            if (row==0):
                pass
            else :
                for col,v in value.items():
                    if (col=="1"):
                        metric.set('id',str(data[row][col]))
                    if (col=="2"):
                        metric.set('description',str(data[row][col]))
                    if (col=="3"):
                        if (str(data[row][col]).startswith("E")):
                            metric.find('{http://standards.iso.org/iso-iec/19086/-2/ed-1/en}Expression').set("id",str(data[row][col]))
                            metric.find('{http://standards.iso.org/iso-iec/19086/-2/ed-1/en}Expression').set("expressionStatement",str(data[str(int(row)+1)][str(int(col)+1)]))
                            metric.find('{http://standards.iso.org/iso-iec/19086/-2/ed-1/en}Expression').set("expressionLanguage",str(data[str(int(row)+2)][str(int(col)+1)]))
                            metric.find('{http://standards.iso.org/iso-iec/19086/-2/ed-1/en}Expression').set("unit",str(data[str(int(row)+3)][str(int(col)+1)]))
                        elif (str(data[row][col]).startswith("P")):
                            for param in metric.findall('{http://standards.iso.org/iso-iec/19086/-2/ed-1/en}Parameter'):
                                if(str(data[row][col])==param.get('id')):
                                    a=str(data[row][col])
                                    print(str(int(row)+1),str(int(col)+1))
                                    b=str(data[str(int(row)+1)][str(int(col)+1)])
                                    c=str(data[str(int(row)+2)][str(int(col)+1)])
                                    param.set("id",a)
                                    param.set("parameterStatement",b)
                                    param.set("unit",c)
                                else:
                                    pass
                        elif (str(data[row][col]).startswith("R")):
                            for rule in metric.findall('{http://standards.iso.org/iso-iec/19086/-2/ed-1/en}Rule'):
                                if(str(data[row][col])==rule.get('id')):
                                    a=str(data[row][col])
                                    b=str(data[str(int(row)+1)][str(int(col)+1)])
                                    rule.set("id",a)
                                    rule.set("ruleStatement",b)
                                else :
                                    pass

However, I have a KeyError on the line where b is assigned. I have tried to print row and col and checked if row+1 and col+1 are keys, and they are.

In the case where the program crashes row=6 and col=3 so there is a value at this emplacement but it is also true for row=7 and col=4, and I have : KeyError :'7'


Solution

  • for row,value in data.items() :
        for col,v in value.items():
            a=data[row][col]
            b=data[row+1][str(int(col)+1)]
    

    But at point row=4 and col=4, you will get error, cause there is no data[5]['5'] element in data.

    Please, notice that data['4'] and data[4] are different things. That's why you need to get dict element by correct key.