Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 751
Natim Avatar asked Nov 19 '10 09:11

Natim


2 Answers

Here is my solution :

def lower_key(in_dict):
    if type(in_dict) is dict:
        out_dict = {}
        for key, item in in_dict.items():
            out_dict[key.lower()] = lower_key(item)
        return out_dict
    elif type(in_dict) is list:
        return [lower_key(obj) for obj in in_dict]
    else:
        return in_dict
like image 68
Natim Avatar answered Oct 15 '22 12:10

Natim


>>> 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}}
like image 42
Fred Nurk Avatar answered Oct 15 '22 12:10

Fred Nurk