如何确保python字典键是小写的?

时间:2021-12-16 00:09:18

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

我有一个用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.

编辑:谢谢你看了我的问题,很抱歉我没有详细解释为什么我想要这个。它是用来修补JSONEmitter的django-活塞。

6 个解决方案

#1


21  

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

#2


8  

Here is a solution that forbids setting a lowercase key:

这里有一个解决方案,禁止设置小写键:

class LowerCaseDict(dict):
    def __setitem__(self, key, val):
        if not key.islower():
            raise TypeError, "%s key must be lowercase" % key
        dict.__setitem__(self, key, val)

ld = LowerCaseDict()
ld['g']='g'

#3


4  

Since you have not mentioned clearly what you want to do:

由于你并没有清楚地说明你想要做什么:

Convert all keys to lowercase:

将所有键转换为小写:

>>> y = dict((k.lower(), v) for k, v in x.iteritems())

Check for keys:

检查键:

>>> for k in x.iterkeys():
    if k.islower():
        print k, 'True'
    else:
        print k, 'False'

#4


2  

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

#5


2  

If you just want to check if they're all lowercase (your wording, using "ensure", is not clear, but I suspect this isn't what you want), you can do that compactly in one line:

如果你只是想检查它们是否都是小写的(你使用的“确保”的措辞不清楚,但我怀疑这不是你想要的),你可以在一行内完成:

all(k.islower() for k in x.iterkeys())

#6


2  

Here is a complete solution

这是一个完整的解决方案

from requests import CaseInsensitiveDict

Or if you want to see the code:

或者如果你想看代码:

class CaseInsensitiveDict(dict):

    """Basic case insensitive dict with strings only keys."""

    proxy = {}

    def __init__(self, data):
        self.proxy = dict((k.lower(), k) for k in data)
        for k in data:
            self[k] = data[k]

    def __contains__(self, k):
        return k.lower() in self.proxy

    def __delitem__(self, k):
        key = self.proxy[k.lower()]
        super(CaseInsensitiveDict, self).__delitem__(key)
        del self.proxy[k.lower()]

    def __getitem__(self, k):
        key = self.proxy[k.lower()]
        return super(CaseInsensitiveDict, self).__getitem__(key)

    def get(self, k, default=None):
        return self[k] if k in self else default

    def __setitem__(self, k, v):
        super(CaseInsensitiveDict, self).__setitem__(k, v)
        self.proxy[k.lower()] = k

#1


21  

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

#2


8  

Here is a solution that forbids setting a lowercase key:

这里有一个解决方案,禁止设置小写键:

class LowerCaseDict(dict):
    def __setitem__(self, key, val):
        if not key.islower():
            raise TypeError, "%s key must be lowercase" % key
        dict.__setitem__(self, key, val)

ld = LowerCaseDict()
ld['g']='g'

#3


4  

Since you have not mentioned clearly what you want to do:

由于你并没有清楚地说明你想要做什么:

Convert all keys to lowercase:

将所有键转换为小写:

>>> y = dict((k.lower(), v) for k, v in x.iteritems())

Check for keys:

检查键:

>>> for k in x.iterkeys():
    if k.islower():
        print k, 'True'
    else:
        print k, 'False'

#4


2  

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

#5


2  

If you just want to check if they're all lowercase (your wording, using "ensure", is not clear, but I suspect this isn't what you want), you can do that compactly in one line:

如果你只是想检查它们是否都是小写的(你使用的“确保”的措辞不清楚,但我怀疑这不是你想要的),你可以在一行内完成:

all(k.islower() for k in x.iterkeys())

#6


2  

Here is a complete solution

这是一个完整的解决方案

from requests import CaseInsensitiveDict

Or if you want to see the code:

或者如果你想看代码:

class CaseInsensitiveDict(dict):

    """Basic case insensitive dict with strings only keys."""

    proxy = {}

    def __init__(self, data):
        self.proxy = dict((k.lower(), k) for k in data)
        for k in data:
            self[k] = data[k]

    def __contains__(self, k):
        return k.lower() in self.proxy

    def __delitem__(self, k):
        key = self.proxy[k.lower()]
        super(CaseInsensitiveDict, self).__delitem__(key)
        del self.proxy[k.lower()]

    def __getitem__(self, k):
        key = self.proxy[k.lower()]
        return super(CaseInsensitiveDict, self).__getitem__(key)

    def get(self, k, default=None):
        return self[k] if k in self else default

    def __setitem__(self, k, v):
        super(CaseInsensitiveDict, self).__setitem__(k, v)
        self.proxy[k.lower()] = k