首页 > 解决方案 > 将字典作为具有不同键名的参数传递

问题描述

我对 python 比较陌生,但我仍然在思考 pythonic 方式时遇到问题。我有一个函数,它已经CustomerAdd(id_type, id, name, email, adress, phone_number)并且想要将客户作为参数传递:CustomerAdd(**customer)

我遇到的问题是预期的客户格式是:

{
  "name": [
    "CustName"
  ],
  "address": [
    "CustAddress"
  ],
  "id_type": "passport",
  "id": "123123123",
  "email": "test@email.com",
  "phone_number": "123123"
}

我的客户输入如下所示:

{
  "id_type": "passport",
  "id": "123123123",
  "customer_name": "Gordon Gekko",
  "customer_address": "Fake Street 123",
  "phone_number": "123456789",
  "email": "customer@aol.com"
}

因此,如您所见,我需要更改 customer_name 和 customer_address 的键名,并将值的类型更改为列表。

我能够通过以下方式更改键名:

customer = old_customer.copy()
customer['name'] = customer.pop('customer_name')
customer['address'] = customer.pop('customer_address')

但仍然无法更改值类型。有任何想法吗?或任何其他pythonic方法来解决这个问题?

谢谢

标签: pythondictionary

解决方案


如果它们需要成为列表,只需将它们设为列表:

customer['name'] = [customer.pop('customer_name')]
customer['address'] = [customer.pop('customer_address')]

推荐阅读