2

我有以下字符串:

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'

我怎样才能从中做出查询。

我希望能够使用item['amount']which 返回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

4 回答 4

7

您可以将整个字符串替换为 Django 的 QueryDict |&

请参阅QueryDict 文档

例如

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']}>
于 2012-04-12T10:44:13.447 回答
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']

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

于 2012-04-12T10:21:57.390 回答
1

去做:

>>> {i.split("=")[0]:i.split("=")[1] for i in string.split('|')}
于 2012-04-12T10:21:41.600 回答
0
dict(e.split("=", 1) for e in string.split("|"))
于 2012-04-12T10:21:29.577 回答