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

How to map and update python dictionary with different key value pair?

我想将 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"

    }

如果要转换,不需要copy到原字典。

就像这样:

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]

我觉得把值变成单词数组再解析会更容易。此处,从字典字符串“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'}