Reputation: 2370
I have the following string:
string = 'amount=2000|captureDay=0|captureMode=AUTHOR_CAPTURE|currencyCode=978|merchantId=002020000000001|orderId=|transactionDateTime=2012-04-12T12:09:56+02:00|transactionReference=1212943|keyVersion=1|authorisationId=0020000006791167|complementaryCode=|maskedPan=|paymentMeanBrand=IDEAL|paymentMeanType=CREDIT_TRANSFER|responseCode=00'
How can i make a querydict out of this.
I want to be able to use item['amount']
which returns 2000
EDIT:
what i've tried so far:
dict = string.split('|')
Output is:
['amount=2000', 'captureDay=0', 'captureMode=AUTHOR_CAPTURE', 'currencyCode=978', 'merchantId=002020000000001', 'orderId=', 'transactionDateTime=2012-04-12T12:09:56+02:00', 'transactionReference=1212943', 'keyVersion=1', 'authorisationId=0020000006791167', 'complementaryCode=', 'maskedPan=', 'paymentMeanBrand=IDEAL', 'paymentMeanType=CREDIT_TRANSFER', 'responseCode=00']
Upvotes: 2
Views: 8357
Reputation: 22858
string = 'amount=2000|captureDay=0|captureMode=AUTHOR_CAPTURE|currencyCode=978|merchantId=002020000000001|orderId=|transactionDateTime=2012-04-12T12:09:56+02:00|transactionReference=1212943|keyVersion=1|authorisationId=0020000006791167|complementaryCode=|maskedPan=|paymentMeanBrand=IDEAL|paymentMeanType=CREDIT_TRANSFER|responseCode=00'
items = dict(item.split('=', 1) for item in string.split('|'))
print items['amount']
The first split (on the pipe symbol) yields a list of strings in "x=y" format. The second split takes each of these and returns a list of two elements. This list of 2-element lists is then fed into the dict()
constructor.
Upvotes: 3
Reputation: 38265
You could substitute |
with &
and give the whole string to Django's QueryDict.
See the QueryDict documenation
E.g.
In [1]: from django.http import QueryDict
In [2]: sample = 'amount=2000|captureDay=0|captureMode=AUTHOR_CAPTURE|currencyCode=978|merchantId=002020000000001|orderId=|transactionDateTime=2012-04-12T12:09:56+02:00|transactionReference=1212943|keyVersion=1|authorisationId=0020000006791167|complementaryCode=|maskedPan=|paymentMeanBrand=IDEAL|paymentMeanType=CREDIT_TRANSFER|responseCode=00'
In [3]: qdict = QueryDict(sample.replace('|','&'))
In [4]: qdict
Out[4]: <QueryDict: {u'orderId': [u''], u'keyVersion': [u'1'], u'transactionReference': [u'1212943'], u'paymentMeanType': [u'CREDIT_TRANSFER'], u'maskedPan': [u''], u'currencyCode': [u'978'], u'paymentMeanBrand': [u'IDEAL'], u'complementaryCode': [u''], u'amount': [u'2000'], u'authorisationId': [u'0020000006791167'], u'responseCode': [u'00'], u'captureMode': [u'AUTHOR_CAPTURE'], u'captureDay': [u'0'], u'transactionDateTime': [u'2012-04-12T12:09:56 02:00'], u'merchantId': [u'002020000000001']}>
Upvotes: 7
Reputation: 2539
Go for:
>>> {i.split("=")[0]:i.split("=")[1] for i in string.split('|')}
Upvotes: 1