Querydict一个字符串

时间:2012-04-12 10:17:57

标签: python django

我有以下字符串:

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'

我如何从中做出一个querydict。

我希望能够使用item['amount']返回2000

编辑:

到目前为止我尝试了什么:

dict = string.split('|')

输出是:

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

4 个答案:

答案 0 :(得分:7)

您可以将|替换为&,并将整个字符串提供给Django的QueryDict。

请参阅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']}>

答案 1 :(得分:3)

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

第一个分割(在管道符号上)产生一个字符串列表,在&#34; x = y&#34;格式。第二个拆分采用其中的每一个并返回两个元素的列表。然后将此2元素列表列表输入dict()构造函数。

答案 2 :(得分:1)

Go for:

>>> {i.split("=")[0]:i.split("=")[1] for i in string.split('|')}

答案 3 :(得分:0)

dict(e.split("=", 1) for e in string.split("|"))