How to ensure that a python dict keys are lowercase?

主宰稳场 提交于 2019-11-30 19:42:59
>>> 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}}

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'

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

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'

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())

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!