如何用不同的键值对映射和更新python字典?



我想在Python中转换字典,从字典1到字典2,如下所示。

transaction = {
"trans_time": "14/07/2015 10:03:20",
"trans_type": "DEBIT",
"description": "239.95 USD DHL.COM TEXAS USA",
}

我想把上面的字典转换成下面的

transaction =  {
"trans_time": "14/07/2015 10:03:20",
"trans_type": "DEBIT",
"description": "DHL.COM TEXAS USA",
"amount": 239.95,
"currency": "USD",
"location": "TEXAS USA",
"merchant_name": "DHL"

}

我尝试了以下操作,但没有成功

dic1 = {
"trans_time": "14/07/2015 10:03:20",
"trans_type": "DEBIT",
"description": "239.95 USD DHL.COM TEXAS USA"
}
print(type(dic1))
copiedDic = dic1.copy()
print("copiedDic = ",copiedDic)

updatekeys = ['amount', 'currency', 'merchant_name', 'location', 'trans_category']

for key in dic1:
if key == 'description':
list_words = dic1[key].split(" ")
newdict =  {updatekeys[i]: x for i, x in enumerate(list_words)}
copiedDic.update(newdict)
print(copiedDic)

我得到了以下结果

{
'trans_time': '14/07/2015 10:03:20',
'trans_type': 'DEBIT', 
'description': '239.95 USD DHL.COM TEXAS USA',
'amount': '239.95',
'currency': 'USD',
'merchant_name': 'DHL.COM',
'location': 'TEXAS',
'trans_category': 'USA'
}

我的预期输出应该是这样的:

transaction =  {
"trans_time": "14/07/2015 10:03:20",
"trans_type": "DEBIT",
"description": "DHL.COM TEXAS USA",
"amount": 239.95,
"currency": "USD",
"location": "TEXAS USA",
"merchant_name": "DHL"
}

我认为将值转换为单词数组并对其进行解析会更容易。在这里,从字典字符串'transaction['description']'创建单词'aaa '数组。如果有多个单词(数组元素)'join'用于将数组转换回字符串。货币值本身从字符串转换为小数格式。在'merchant_name'中,取该点之前的段。

transaction = {
"trans_time": "14/07/2015 10:03:20",
"trans_type": "DEBIT",
"description": "239.95 USD DHL.COM TEXAS USA",
}
aaa = transaction['description'].split()
transaction['description'] = ' '.join(aaa[2:])
transaction['amount'] = float(aaa[0])
transaction['currency'] = aaa[1]
transaction['location'] = ' '.join(aaa[3:])
transaction['merchant_name'] = aaa[2].partition('.')[0]
print(transaction)

输出
{
'trans_time': '14/07/2015 10:03:20',
'trans_type': 'DEBIT',
'description': 'DHL.COM TEXAS USA',
'amount': 239.95,
'currency': 'USD',
'location': 'TEXAS USA',
'merchant_name': 'DHL'}

如果你想转换,你不需要复制到原来的字典。

就像这样做:

new_keys = ['amount', 'currency', 'merchant_name', 'location', 'trans_category']
values = transaction["description"].split(' ')
for idx, key in enumerate(new_keys):
if key == "amount":
transaction[key] = float(values[idx])
else:
transaction[key] = values[idx]

相关内容

  • 没有找到相关文章

最新更新