如何确保python dict键为小写? [英] How to ensure that a python dict keys are lowercase?

查看:339
本文介绍了如何确保python dict键为小写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,我想使用simplejson进行JSON转换.

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": ""
    },

谢谢大家看我的问题,很抱歉,我没有详细解释为什么要这样做.这是修补django-pistonJSONEmitter.

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.

推荐答案

>>> 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}}

这篇关于如何确保python dict键为小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆