我有一个我通过request
检索的对象,我需要将其映射并规范化为预期的响应:
address_list = list(map(normalize_shipping_address, address_list))
我希望能够设置某种dict来处理映射,例如:
def normalize_shipping_address(address):
normalized_address = {}
valueMapping = {
'firstname': 'firstName',
'lastname': 'lastName',
'city': 'city',
'postcode': 'zip',
'countryId': 'country',
'defaultShipping': 'isDefault',
}
for source_key, destination_key in valueMapping.iteritems():
try:
key = address[source_key]
except KeyError:
key = None
normalized_address[destination_key] = key
return normalized_address
但意识到我没有一个好方法来获取嵌套字典键或列表对象,例如:address.some.nested.key
或address.some.list[0].key
。
我最终处理了这些特殊的案件"通过做以下事情:
try:
state = address['region']['regionCode']
except KeyError:
state = None
normalized_address['state'] = state
和
try:
address_name = address['customAttributes'][0]['value']
except KeyError:
address_name = None
normalized_address['addressName'] = address_name
这似乎有点冗长和笨重。是否有更优雅的方法来解析/规范化这样的词典?