I get a xml response which is in bytes and parsed by xmltodict as shown below. Since I need to further use the response, I want to eliminate all the '@' in the key. I have tried two way to remove the sign but still not working. Are there any method to remove sign in dict?
XML response (resp.text): {'HOLDING_QUERY_RESPONSE': OrderedDict([('@LOGIN_ID', '011'), ('@CLIENT_ID', '011'), ('@CHANNEL', 'MB'), ('@SESSION_KEY', '111'), ('RESULT', OrderedDict([('@STATUS', 'OK'), ('BUYING_POWER', '98’),( 'USD_BUYING_POWER', '12'), ('AVAILABLE_MKT_VAL', '110'), ('CASH_HOLDING', OrderedDict([('LINEITEM', [OrderedDict([('@CURRENCY_CODE', 'USD'), ('@AVAILABLE_BAL', '-233'), ('@CASH_BALANCE', '0.00'), ('@CASH_ON_HOLD', '0.00'), ('@UNSETTLED_CASH', '0.00'), ('@ACCRUED_INTEREST', '0.00'), ('@BUY_SOLD_CONSIDERATION', '-233'), ('@EX_RATE', '1'), ('@AVAILABLE_VAL', '6'), ('@AMT', '0.00'), ('@DUE_AMT', '0.00')]),…….)])])]))]))])}
First tried method. The error is dict object has no attribute 'iteritems()'. If I remove the '.iteritem()', it will show Value Error: too many value to unpack.
info = {key.replace('@',''): item for key, item in xmltodict.parse(resp.text).iteritems()}
print(info)
Second tried method is changed it to string first and then translate it back to dict. But, still it seems the dict has not translate to string by json.dumps.
info = json.dumps(resp.text)
info.replace('@','')
to_dict = json.loads(info)
print(to_dict)
Try this:
info = {key.replace('@',''): item for key, item in xmltodict.parse(resp.text).items()}
print(info)
As mentioned in the comments, xmltodict.parse
returns a dictionary, and in your case, you might be working with Python 3, so use the .items()
attribute to access the dictionary.
As an example:
d = ('@CASH', '0.00'), ('@INTEREST', '0.00'), ('@BUY', '-233'), ('@RATE', '1.000000'), ('@AVAILABLE', '6,228'), ('@AMT', '0.00')
info = {key.replace('@',''): item for key, item in d}
print(info)
>>
{'CASH': '0.00', 'INTEREST': '0.00', 'BUY': '-233', 'RATE': '1.000000', 'AVAILABLE': '6,228', 'AMT': '0.00'}
Updated question soution
Similarly, if it is a nested dictionary, you have to access the key you want to replace @
in its values, from your updated example, you should be able to access the nested dictionary with xmltodict.parse(resp.text)['HOLDING_QUERY_RESPONSE']
.
from collections import OrderedDict
#based on your updated data structure
d = OrderedDict([('@CASH', '0.00'), ('@INTEREST', '0.00'), ('@BUY', '-233'), ('@RATE', '1.000000'), ('@AVAILABLE', '6,228'), ('@AMT', '0.00')])
xml_response = {}
xml_response['HOLDING_QUERY_RESPONSE'] = d
xml_response
{'HOLDING_QUERY_RESPONSE': OrderedDict([('@CASH', '0.00'),
('@INTEREST', '0.00'),
('@BUY', '-233'),
('@RATE', '1.000000'),
('@AVAILABLE', '6,228'),
('@AMT', '0.00')])}
info = {key.replace('@',''):value for key, value in xml_response['HOLDING_QUERY_RESPONSE'].items()}
print(info)