Skip to content

Instantly share code, notes, and snippets.

@kalda341
Created July 18, 2020 22:31
Show Gist options
  • Save kalda341/aa451a8e23c92dc0eea5cca500e54d4f to your computer and use it in GitHub Desktop.
Save kalda341/aa451a8e23c92dc0eea5cca500e54d4f to your computer and use it in GitHub Desktop.
from functools import partial
from stringcase import snakecase
def recursively_convert_keys(conversion_fun, data):
"""
The first major change we're making is pulling the type check out of the loop. This reduces the number of cases
which we need to handle, and allows us to run the conversion with a dictionary or a list.
The second change is that we're not mutating the original input. This simplifies things because we don't have
to delete the old keys, and we don't need to worry about breaking things in code elsewhere.
"""
if isinstance(data, dict):
# Convert keys and recursively process values
return { conversion_fun(k): recursively_convert_keys(conversion_fun, v) for k, v in data.items() }
elif isinstance(data, list):
# Recursively process values
return [recursively_convert_keys(conversion_fun, x) for x in data]
else:
# If data isn't a dictionary or a list then it can be left unchanged
return data
def convert_key(key):
mapping = {
"address1": "route",
"address2": "sublocality",
"address3": "locality",
"post_code": "postal_code",
"country_code": "country",
}
snake_key = snakecase(key)
# Return the value in the mapping dictionary, or the snakecase key if it does not exist.
return mapping.get(snake_key, snake_key)
convert_keys = partial(recursively_convert_keys, convert_key)
a = {
"entity_status_code": "80",
"entity_name": "ASIA PACIFIC DISTRIBUTORS INVESTMENTS NO 2 LIMITED",
"nzbn": "9429035530732",
"entity_type_code": "LTD",
"entity_type_description": "NZ Limited Company",
"entity_status_description": "Removed",
"registration_date": "2003-11-20T00:00:00.000+1300",
"source_register": "COMPANY",
"source_register_unique_identifier": "1447962",
"last_updated_date": "2013-10-18T10:54:28.000+1300",
"australian_business_number": None,
"email_addresses": None,
"addresses": {
"links": None,
"address_list": [
{
"unique_identifier": "7020375",
"start_date": "2003-11-20T00:00:00.000+1300",
"end_date": None,
"care_of": None,
"address1": "87 Braemar Road",
"address2": "Castor Bay",
"address3": "Auckland",
"address4": None,
"post_code": None,
"country_code": "NZ",
"address_type": "REGISTERED",
"paf_id": None
},
]
}
}
print(a)
print(convert_keys(a))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment