Search code examples
pythondictionaryindices

Getting Error while Iterating over Dictionary in Python


My dictionary is below; I get an error while iterating over it.

mk = {'Incident': {'AlertStatus': 'SLA BREACH',
              'Area': 'Test',
              'Assignee': 'Incident.Coordinator',
              'AssignmentGroup': 'Operating System Support (North America)',
              'Category': 'incident',
              'Contact': 'ALSTON, LOU',
              'Description': ['Test - Request - 1 , Test - Request - 1, Test - '
                              'Request - 1Test - Request - 1Test - Request - '
                              '1Test - Request - 1Test - Request - 1Test - '
                              'Request - 1Test - Request - 1'],
              'Impact': '2',
              'IncidentID': 'IM10265',
              'OpenTime': '2020-04-09T08:16:16+00:00',
              'OpenedBy': 'rf',
              'Phase': 'Categorization',
              'Service': 'CI1001032',
              'Source': '2',
              'Status': 'Categorize',
              'Subarea': 'Test',
              'Title': 'Test - Request - 1',
              'UpdatedBy': 'rf',
              'UpdatedTime': '2020-04-09T08:16:25+00:00',
              'Urgency': '3'},
 'Messages': [],
 'ReturnCode': 0}


def extract_val():
    id_data = []
    Assignee_data = []
    id_datas = [q['Incident']['IncidentID'] for q in mk]
    Assignee_datas = [t['Incident']['Assignee'] for t in mk]
    print(id_datas)
    print(Assignee_datas)
extract_val()

getting error as : TypeError: string indices must be integers

Though I'm using key (Incident) to then the other keys like :(Incident), (Assignee) to extract values, still getting error. Please suggest what I'm missing here


Solution

  • If mk is list of dicts try this.

    mk = [{'Incident': {'AlertStatus': 'SLA BR', 'Area': 'Test', 'Assignee': 'Incident.Coordinator','Category': 'incident', 'Contact': 'LU', 'Impact': '2', 'IncidentID': 'IM10265', 'OpenedBy': 'rf', 'Phase': 'OP', 'Service': 'CI102', 'Urgency': '3'}, 'Messages': [], 'ReturnCode': 0}, {'Incident': {'AlertStatus': 'SLA AC', 'Area': 'Test', 'Assignee': 'Cris.Bros', 'AssignGroup': 'FCI', 'Category': 'incident', 'Contact': 'AN', 'Description': ['Test-Request-2'], 'IncidentID': 'IM10266', 'Status': 'WI', 'Subarea': '3', 'Urgency': '1'}, 'Messages': [], 'ReturnCode': 0}]
    def extract_val():
    
        id_datas , Assignee_datas =  map(list, zip(*[(q['Incident']['IncidentID'], q['Incident']['Assignee']) for q in mk]))
        print(id_datas)
        print(Assignee_datas)
    extract_val()
    

    Output:

    ['IM10265', 'IM10266']
    ['Incident.Coordinator', 'Cris.Bros']