Getting Error while Iterating over Dictionary in Python [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
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

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']

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.

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].

Related

Combine some items in list [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 months ago.
Improve this question
I have list like this,
arr = [{"type":"A","name":"1"},
{"type":"B","name":"2"},
{"type":"B","name":"3"},
{"type":"C","name":"4"},
{"type":"B","name":"5"},
{"type":"B","name":"6"},
{"type":"D","name":"7"},
{"type":"B","name":"8"},
{"type":"B","name":"9"},]]
I want to combine type B like this below
Adding pages key
[{"type":"A","name":"1"},
{"type":"B","pages":[
{"type":"B","name":"2"},
{"type":"B","name":"3"}]},
{"type":"C","name":"4"},
{"type":"B","pages":[
{"type":"B","name":"5"},
{"type":"B","name":"6"}
]},
{"type":"D","name":"7"},
{"type":"B","pages":[
{"type":"B","name":"8"},
{"type":"B","name":"9"}
]}
]
I try to do this with loop,
However, still struggling..
Please give me some ideas.
result = []
first = False
for i in arr:
if i['type'] == "B":
if first == False:
first = True
i['pages'] = []
i['pages'].append(i)
else:
i['pages'].append(i)
else:
result.append(i)
flg = False
print(result)
Here's a solution using itertools.groupby:
from itertools import groupby
result = []
for key, group in groupby(arr, key=lambda x: x['type']):
group = list(group)
if len(group) > 1:
result.append({'type': key, 'pages': group})
else:
result.append(group[0])
from pprint import pprint
pprint(result)
Output:
[{'name': '1', 'type': 'A'},
{'pages': [{'name': '2', 'type': 'B'}, {'name': '3', 'type': 'B'}],
'type': 'B'},
{'name': '4', 'type': 'C'},
{'pages': [{'name': '5', 'type': 'B'}, {'name': '6', 'type': 'B'}],
'type': 'B'},
{'name': '7', 'type': 'D'},
{'pages': [{'name': '8', 'type': 'B'}, {'name': '9', 'type': 'B'}],
'type': 'B'}]

Sending python requests and handling JSON lists

I am sending requests to a crypto network for data on accounts. You get sent back information, but I haven't yet encountered lists being sent in JSON until now. I want to parse certain information, but am having trouble because the JSON is a list and is not as easy to parse compared to normal JSON data.
import requests
import json
url = ' https://s1.ripple.com:51234/'
payload = {
"method": "account_objects",
"params": [
{
"account": "r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59",
"ledger_index": "validated",
"type": "state",
"deletion_blockers_only": False,
"limit": 10
}
]
}
response = requests.post(url, data=json.dumps(payload))
print(response.text)
data = response.text
parsed = json.loads(data)
price = parsed['result']
price = price['account_objects']
for Balance in price:
print(Balance)
You will receive all the tokens the account holds and the value. I can not figure out how to parse this correctly and receive the correct one. This particular test account has a lot of tokens so I will only show the first tokens info.
RESULT
{'Balance': {'currency': 'ASP', 'issuer': 'rrrrrrrrrrrrrrrrrrrrBZbvji', 'value': '0'}, 'Flags': 65536, 'HighLimit': {'currency': 'ASP', 'issuer': 'r9cZA1mLK5R5Am25ArfXFmqgNwjZgnfk59', 'value': '0'}, 'HighNode': '0', 'LedgerEntryType': 'RippleState', 'LowLimit': {'currency': 'ASP', 'issuer': 'r3vi7mWxru9rJCxETCyA1CHvzL96eZWx5z', 'value': '10'}, 'LowNode': '0', 'PreviousTxnID': 'BF7555B0F018E3C5E2A3FF9437A1A5092F32903BE246202F988181B9CED0D862', 'PreviousTxnLgrSeq': 1438879, 'index': '2243B0B630EA6F7330B654EFA53E27A7609D9484E535AB11B7F946DF3D247CE9'}
I want to get the first bit of info, here. {'Balance': {'currency': 'ASP', 'issuer': 'rrrrrrrrrrrrrrrrrrrrBZbvji', 'value': '0'},
Specifically 'value' and the number
I have tried to take parse 'Balance' but since it is a list it is not as straight forward.
You're mixing up lists and dictionaries. In order to access a dictionary by key, you need to invoke the key, as such:
for Balance in price:
print(Balance['Balance'])
Yields the following results:
{'currency': 'CHF', 'issuer': 'rrrrrrrrrrrrrrrrrrrrBZbvji', 'value': '-0.3488146605801446'}
{'currency': 'BTC', 'issuer': 'rrrrrrrrrrrrrrrrrrrrBZbvji', 'value': '0'}
{'currency': 'USD', 'issuer': 'rrrrrrrrrrrrrrrrrrrrBZbvji', 'value': '-11.68225001668339'}
If you only wanted to extract the value, you simply dive one level deeper:
for Balance in price:
print(Balance['Balance']['value')
Which yields:
-0.3488146605801446
0
-11.68225001668339
I assume that under price['account_objects'] you have a list of dictionaries? And then in each dictionary you have in one of the keys: 'Balance': {'currency': 'ASP', 'issuer': 'rrrrrrrrrrrrrrrrrrrrBZbvji', 'value': '0'. If so, why don't you iterate over the list and then access each dictionary, like:
account_objects = price['account_objects']
for account_object in price:
print(account_object['Balance'])

Show question from surveygizmo survey using API Python

im using an API to get some responses from surveygizmo. It works, but it is changing the question to [question(1)], [question(2)]...
import surveygizmo as sg
client = sg.SurveyGizmo(
api_version='v4',
# example
api_token = "api_token",
api_token_secret = "api_token_secret."
)
survey_id = "survey_id"
responses = client.api.surveyresponse.list(survey_id)
pages = responses['total_pages']
data = []
responses
I got the following answer:
{'result_ok': True,
'total_count': 5,
'page': 1,
'total_pages': 1,
'results_per_page': 50,
'data': [{'id': '1',
'contact_id': '',
'status': 'Complete',
'is_test_data': '0',
'datesubmitted': '2020-01-22 16:07:30',
'SessionID': '1579727226_5e28b97a9ff992.53369554',
'Language': 'Portuguese (Brazil)',
'datestarted': '2020-01-22 16:07:30',
'iLinkID': '9342723',
'sResponseComment': '',
'responseID': '1',
'[question(2)]': 'Sim',
'[question(3)]': 'Assunto',
'[question(4)]': '8',
...
I need to show the question as it was made. How it is possible to do that?
I found the answer. api_version='v4' has some limitations, the question text came with api_version='v5'.

How to modify the values of a dictionary from a list of dictionaries

I am declaring a method named add_to_cart(db, itemid, quantity). Whenever the method is called, it will look into the database for the session data. Session data contains a list of dictionaries. The purpose of this method is to create a new entry (dictionary) to the list or update the value of existing entry.
Dictionary has the following keys: id, quantity
So far I have developed the following code. First of all after fetching the data from the database, I am matching the itemid with the dictionary key: 'id'. If the itemid does not match with any of the values of the dictionaries, then it will append a new dictionary to that list.
def add_to_cart(db, itemid, quantity):
# ......
row = cursor.fetchone()
if row is not None:
cart = json.loads(row['data'])
for dic in cart:
if str(dic.get("id")) == str(itemid):
dic['quantity'] = int(dic['quantity']) + quantity
data = json.dumps(cart)
# update the 'data' to the database
break
else:
if counter == len(cart):
item = {
'id': itemid,
'quantity': quantity
}
cart.append(item)
data = json.dumps(cart)
# update the 'data' to the database
break
Let the initial cart is like:
[{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}]
When I add 1 more of the item 40 to the cart, this should be like:
[{'id': '40', 'quantity': '3'}, {'id': '41', 'quantity': '5'}]
but I am getting :
[{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}, {'id': '40', 'quantity': '1'}]
You are adding a new dictionary to the list when you do cart.append(item),
hence the list
[{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}]
ends up being
[{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}, {'id': '40', 'quantity': '1'}]
But you want to find the matching id in that list of dictionaries, and add to the quantity for that dictionary.
So the code will look like as below:
li = [{'id': '40', 'quantity': '2'}, {'id': '41', 'quantity': '5'}]
def add_elem(li, id, to_add):
#Iterate over the dictionaries
for item in li:
#If the id is found
if str(id) in item.values():
#Increment the quantity
item['quantity'] = str(int(item['quantity']) + to_add)
#Return the updated list
return li
print(add_elem(li, 40, 1))
The output will be
[{'id': '40', 'quantity': '3'}, {'id': '41', 'quantity': '5'}]
The problem seems to be that you are going simply adding a new dict to the list (cart), through append. You need to go through the list, find the dict with the itemid you need, then add to the quantity.
Try this -
for dict in cart:
if dict[itemid] == itemid:
dict['quantity'] += str(quantity)
break
item = {
'id': itemid,
'quantity': quantity
}
cart.append(item)

How do I get the 'Resolution' from Jira with python and XML-RPC

I'm using python to fetch issues from Jira with xml-rpc. It works well except it is missing the 'Resolution' field in the returned dictionary. For example 'Fixed', or 'WontFix' etc.
This is how I get the issue from Jira:
import xmlrpclib
s = xmlrpclib.ServerProxy('http://myjira.com/rpc/xmlrpc')
auth = s.jira1.login('user', 'pass')
issue = s.jira1.getIssue(auth, 'PROJ-28')
print issue.keys()
And this is the list of fields that I get back:
['status', 'project', 'attachmentNames', 'votes', 'updated',
'components', 'reporter', 'customFieldValues', 'created',
'fixVersions', 'summary', 'priority', 'assignee', 'key',
'affectsVersions', 'type', 'id', 'description']
The full content is:
{'affectsVersions': [{'archived': 'false',
'id': '11314',
'name': 'v3.09',
'released': 'false',
'sequence': '7'}],
'assignee': 'myuser',
'attachmentNames': '2011-08-17_attach.tar.gz',
'components': [],
'created': '2011-06-14 12:33:54.0',
'customFieldValues': [{'customfieldId': 'customfield_10040', 'values': ''},
{'customfieldId': 'customfield_10010',
'values': 'Normal'}],
'description': "Blah blah...\r\n",
'fixVersions': [],
'id': '28322',
'key': 'PROJ-28',
'priority': '3',
'project': 'PROJ',
'reporter': 'myuser',
'status': '1',
'summary': 'blah blah...',
'type': '1',
'updated': '2011-08-18 15:41:04.0',
'votes': '0'}
When I do:
resolutions = s.jira1.getResolutions(auth )
pprint.pprint(resolutions)
I get:
[{'description': 'A fix for this issue is checked into the tree and tested.',
'id': '1',
'name': 'Fixed'},
{'description': 'The problem described is an issue which will never be fixed.',
'id': '2',
'name': "Won't Fix"},
{'description': 'The problem is a duplicate of an existing issue.',
'id': '3',
'name': 'Duplicate'},
{'description': 'The problem is not completely described.',
'id': '4',
'name': 'Incomplete'},
{'description': 'All attempts at reproducing this issue failed, or not enough information was available to reproduce the issue. Reading the code produces no clues as to why this behavior would occur. If more information appears later, please reopen the issue.',
'id': '5',
'name': 'Cannot Reproduce'},
{'description': 'Code is checked in, and is, er, ready for build.',
'id': '6',
'name': 'Ready For Build'},
{'description': 'Invalid bug', 'id': '7', 'name': 'Invalid'}]
The Jira version is v4.1.1#522 and I using Python 2.7.
Any ideas why I don't get a field called 'resolution'?
Thanks!
The answer is that the getIssue method in JiraXmlRpcService.java calls makeIssueStruct with a RemoteIssue object. The RemoteIssue object contains the Resolution field, but makeIssueStruct copies only values that are set. So if Resolution is not set, it won't appear in the Hashtable there.

Categories