pythonjsonsimplejsondjango-piston

How to ensure that a python dict keys are lowercase?


I have a dict that I want to convert in JSON using simplejson.

How can I ensure that all the keys of my dict are lowercase ?

    {
        "DISTANCE": 17.059918745802999, 
        "name": "Foo Bar", 
        "Restaurant": {
            "name": "Foo Bar", 
            "full_address": {
                "country": "France", 
                "street": "Foo Bar", 
                "zip_code": "68190", 
                "city": "UNGERSHEIM"
            }, 
            "phone": "+33.389624300", 
            "longitude": "7.3064454", 
            "latitude": "47.8769091", 
            "id": "538"
        }, 
        "price": "", 
        "composition": "", 
        "profils": {}, 
        "type_menu": "", 
        "ID": ""
    },

EDIT: Thanks all to had a look at my question, I am sorry I didn't explain in detailed why I wanted this. It was to patch the JSONEmitter of django-piston.


Solution

  • >>> d = {"your": "DATA", "FROM": "above"}
    >>> dict((k.lower(), v) for k, v in d.iteritems())
    {'from': 'above', 'your': 'DATA'}
    >>> def lower_keys(x):
    ...   if isinstance(x, list):
    ...     return [lower_keys(v) for v in x]
    ...   elif isinstance(x, dict):
    ...     return dict((k.lower(), lower_keys(v)) for k, v in x.iteritems())
    ...   else:
    ...     return x
    ...
    >>> lower_keys({"NESTED": {"ANSWER": 42}})
    {'nested': {'answer': 42}}