-1

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

Prune
  • 76,765
  • 14
  • 60
  • 81
Oxxodome
  • 13
  • 4
  • there is a syntax error in your dictionary. did you notice that? – Mahdi Sorkhmiri Apr 28 '20 at 05:35
  • Not only that, you're missing the indentation in your question. If you fix both your code will show `['IM10265', 'IM10266'] ['Incident.Coordinator', 'Cris.Bros']`. Is that the exepcted result? – SergioR Apr 28 '20 at 05:46
  • Well, what is `q` at the point of error? `print` statements are your first debugging tool. – Prune Apr 28 '20 at 05:52
  • Yes that's the expected result: ['IM10265', 'IM10266'] ['Incident.Coordinator', 'Cris.Bros'] – Oxxodome Apr 28 '20 at 08:35

3 Answers3

0

Let's print and you'll see your problem...

>>> for q in mk:
...     print(q)
...
Incident
Messages
ReturnCode

Wen looping through dict like this, you loop through keys.

But I suppose your problem is that you are excepting to have list of that kind of dictionary objects. If so, your function works as expected.

ex4
  • 2,289
  • 1
  • 14
  • 21
0

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']
deadshot
  • 8,881
  • 4
  • 20
  • 39
  • Hi Kormatiraju032, When I'm trying to use your suggestion I'm getting Output as :['IM10271'] ['Cris.Bros'] While I'm trying to build as list like: ['IM10265', 'IM10271'] ['Incident.Coordinator', 'Cris.Bros'] – Oxxodome Apr 28 '20 at 07:18
  • on which dictionary you are testing this and can you add it in the post i will check – deadshot Apr 28 '20 at 07:31
  • here is the dictionary: 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} – Oxxodome Apr 28 '20 at 08:08
  • @Oxxodome i am getting expected output may be your input is in wrong format check once – deadshot Apr 28 '20 at 08:35
  • I cant post the complete code here, Please suggest how can i share the complete code as the space here is less, Also I can see in your example dictionary mk = [{......}], while the dictionary mk im using is {.........}, so may be in your code example it is considered as list & possibly it may not be working!!! – Oxxodome Apr 28 '20 at 09:03
  • the dictionary you share is not a valid dictionay `mk = {} {}` is it a dictionary – deadshot Apr 28 '20 at 09:06
  • Basically I'm querying a RestAPI which is returning me multiple dictionaries and I just appending it d = [1434, 234534, 33754] mk = { } responses = [ ] for d in new_list: urle = "http://IP:Port/SM/9/rest/incidents/{}".format(d) sm_1 = requests.get(urle, auth=('a','q')) mk = json.loads(sm_1.text) responses.append(mk) print(mk) – Oxxodome Apr 28 '20 at 09:19
  • output of mk dictionary looks like what I have shared above & you got it correctly, mk = {} {} – Oxxodome Apr 28 '20 at 09:20
  • each dictionary must be separated by comma if you have multiple dictionaries and above format is not valid in python. If you want to share the full code you can use pastebin – deadshot Apr 28 '20 at 09:21
  • Here the **pastebin url** : https://pastebin.com/NJbxLY76 , Thanks in advance for your efforts and support – Oxxodome Apr 28 '20 at 09:37
  • just replace `mk` with `responses` in `extract_val()` it will work – deadshot Apr 28 '20 at 09:43
  • Komatiraju032, it worked perfectly after replacing with responses, Can you just give me a 1 line understanding of the map(list, zip(*[(q['Incident']['IncidentID'], q['Incident']['Assignee']) for q in responses])) you suggested. Thanks in adavance – Oxxodome Apr 28 '20 at 09:51
  • `zip()` produces iterator as a result. I am converting iterator object to list using the `map()` – deadshot Apr 28 '20 at 09:58
0

In the following code line:

id_datas = [q['Incident']['IncidentID'] for q in mk]

You are looping through the keys of the dictionary mk. What you want to do is loop through the items. This can de done using the dict.items() method.

Try the following:

id_datas = [q['Incident']['IncidentID'] for q in mk.items()]

EDIT:
My apologies, here is a solution that works when I try it with your dictionary.

 id_datas = [q[1]['IncidentID'] for q in mk.items() if q[0] == 'Incident']

So mk.items() returns a list of tuples. Each tuple is in the format (key, value) In my example q therefore loops through mk, and if the key q[0] is 'Incident', it returns the 'IncidentID' value from the dictionary returned by q[1].

Morne
  • 11
  • 3
  • Hi Morne, Thanks for your suggestion, but when I'm trying to apply the same I'm getting the error as : **TypeError**: tuple indices must be integers or slices, not str , I also tried like this but was not sure!!! – Oxxodome Apr 28 '20 at 07:25