Python中字典转小写

发布于 2024-07-17 02:56:47 字数 93 浏览 9 评论 0原文

我希望这样做,但是对于字典:

"My string".lower()

是否有内置函数或者我应该使用循环?

I wish to do this but for a dictionary:

"My string".lower()

Is there a built in function or should I use a loop?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

挽清梦 2024-07-24 02:56:47

您将需要使用循环或列表/生成器理解。 如果你想小写所有的键和值,你可以这样做::

dict((k.lower(), v.lower()) for k,v in {'My Key':'My Value'}.iteritems())

如果你只想小写键,你可以这样做::

dict((k.lower(), v) for k,v in {'My Key':'My Value'}.iteritems())

生成器表达式(上面使用的)在构建字典时通常很有用; 我一直在使用它们。 循环理解的所有表现力,没有任何内存开销。

You will need to use either a loop or a list/generator comprehension. If you want to lowercase all the keys and values, you can do this::

dict((k.lower(), v.lower()) for k,v in {'My Key':'My Value'}.iteritems())

If you want to lowercase just the keys, you can do this::

dict((k.lower(), v) for k,v in {'My Key':'My Value'}.iteritems())

Generator expressions (used above) are often useful in building dictionaries; I use them all the time. All the expressivity of a loop comprehension with none of the memory overhead.

因为看清所以看轻 2024-07-24 02:56:47

Python 3 中的更短方法: {k.lower(): v for k, v in my_dict.items()}

Shorter way in python 3: {k.lower(): v for k, v in my_dict.items()}

芸娘子的小脾气 2024-07-24 02:56:47

如果您想要多嵌套字典(json 格式)的键和值小写,这可能会有所帮助。
需要支持 Python 2.7 中应有的字典理解

dic = {'A':['XX', 'YY', 'ZZ'],
       'B':(u'X', u'Y', u'Z'),
       'C':{'D':10,
            'E':('X', 'Y', 'Z'),
            'F':{'X', 'Y', 'Z'}
           },
       'G':{'X', 'Y', 'Z'}
      }

PYTHON2.7 - 还支持 OrderedDict

def _lowercase(obj):
    """ Make dictionary lowercase """
    if isinstance(obj, dict):
        t = type(obj)()
        for k, v in obj.items():
            t[k.lower()] = _lowercase(v)
        return t
    elif isinstance(obj, (list, set, tuple)):
        t = type(obj)
        return t(_lowercase(o) for o in obj)
    elif isinstance(obj, basestring):
        return obj.lower()
    else:
        return obj 

PYTHON 3.6

def _lowercase(obj):
    """ Make dictionary lowercase """
    if isinstance(obj, dict):
        return {k.lower():_lowercase(v) for k, v in obj.items()}
    elif isinstance(obj, (list, set, tuple)):
        t = type(obj)
        return t(_lowercase(o) for o in obj)
    elif isinstance(obj, str):
        return obj.lower()
    else:
        return obj

If you want keys and values of multi-nested dictionary (json format) lowercase, this might help.
Need to have support for dict comprehensions what should be in Python 2.7

dic = {'A':['XX', 'YY', 'ZZ'],
       'B':(u'X', u'Y', u'Z'),
       'C':{'D':10,
            'E':('X', 'Y', 'Z'),
            'F':{'X', 'Y', 'Z'}
           },
       'G':{'X', 'Y', 'Z'}
      }

PYTHON2.7 -- also supports OrderedDict

def _lowercase(obj):
    """ Make dictionary lowercase """
    if isinstance(obj, dict):
        t = type(obj)()
        for k, v in obj.items():
            t[k.lower()] = _lowercase(v)
        return t
    elif isinstance(obj, (list, set, tuple)):
        t = type(obj)
        return t(_lowercase(o) for o in obj)
    elif isinstance(obj, basestring):
        return obj.lower()
    else:
        return obj 

PYTHON 3.6

def _lowercase(obj):
    """ Make dictionary lowercase """
    if isinstance(obj, dict):
        return {k.lower():_lowercase(v) for k, v in obj.items()}
    elif isinstance(obj, (list, set, tuple)):
        t = type(obj)
        return t(_lowercase(o) for o in obj)
    elif isinstance(obj, str):
        return obj.lower()
    else:
        return obj
注定孤独终老 2024-07-24 02:56:47

以下内容与 Rick Copeland 的答案相同,只是在没有使用生成器表达式的情况下编写的:

outdict = {}
for k, v in {'My Key': 'My Value'}.iteritems():
    outdict[k.lower()] = v.lower()

生成器表达式、列表理解和(在 Python 2.7 及更高版本中)字典理解基本上是重写循环的方法。

在 Python 2.7+ 中,您可以使用字典理解(它是一行代码,但您可以重新格式化它们以使其更具可读性):

{k.lower():v.lower()
    for k, v in
    {'My Key': 'My Value'}.items()
}

它们通常比等效的循环更整洁,因为您不必初始化空字典/列表/等..但是,如果您需要做的不仅仅是单个函数/方法调用,它们很快就会变得混乱。

The following is identical to Rick Copeland's answer, just written without a using generator expression:

outdict = {}
for k, v in {'My Key': 'My Value'}.iteritems():
    outdict[k.lower()] = v.lower()

Generator-expressions, list comprehension's and (in Python 2.7 and higher) dict comprehension's are basically ways of rewriting loops.

In Python 2.7+, you can use a dictionary comprehension (it's a single line of code, but you can reformat them to make it more readable):

{k.lower():v.lower()
    for k, v in
    {'My Key': 'My Value'}.items()
}

They are quite often tidier than the loop equivalent, as you don't have to initialise an empty dict/list/etc.. but, if you need to do anything more than a single function/method call they can quickly become messy.

朕就是辣么酷 2024-07-24 02:56:47

这将小写你所有的字典键。 即使您有嵌套的字典或列表。 您可以执行类似的操作来应用其他转换。

def lowercase_keys(obj):
  if isinstance(obj, dict):
    obj = {key.lower(): value for key, value in obj.items()}
    for key, value in obj.items():         
      if isinstance(value, list):
        for idx, item in enumerate(value):
          value[idx] = lowercase_keys(item)
      obj[key] = lowercase_keys(value)
  return obj 
json_str = {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}], "EMB_DICT": {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}]}}

lowercase_keys(json_str)


Out[0]: {'foo': 'BAR',
 'bar': 123,
 'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}],
 'emb_dict': {'foo': 'BAR',
  'bar': 123,
  'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}]}}

This will lowercase all your dict keys. Even if you have nested dict or lists. You can do something similar to apply other transformations.

def lowercase_keys(obj):
  if isinstance(obj, dict):
    obj = {key.lower(): value for key, value in obj.items()}
    for key, value in obj.items():         
      if isinstance(value, list):
        for idx, item in enumerate(value):
          value[idx] = lowercase_keys(item)
      obj[key] = lowercase_keys(value)
  return obj 
json_str = {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}], "EMB_DICT": {"FOO": "BAR", "BAR": 123, "EMB_LIST": [{"FOO": "bar", "Bar": 123}, {"FOO": "bar", "Bar": 123}]}}

lowercase_keys(json_str)


Out[0]: {'foo': 'BAR',
 'bar': 123,
 'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}],
 'emb_dict': {'foo': 'BAR',
  'bar': 123,
  'emb_list': [{'foo': 'bar', 'bar': 123}, {'foo': 'bar', 'bar': 123}]}}
慕烟庭风 2024-07-24 02:56:47

我首先使用 JSON 库反序列化字典,应用小写而不是转换回字典

import json
mydict = {'UPPERCASE': 'camelValue'}
print(mydict)
mydict_in_str = json.dumps(mydict)
mydict_lowercase = json.loads(mydict_in_str.lower())
print(mydict_lowercase)

I used JSON library to deserialize the dictionary first, apply lower case than convert back to dictionary

import json
mydict = {'UPPERCASE': 'camelValue'}
print(mydict)
mydict_in_str = json.dumps(mydict)
mydict_lowercase = json.loads(mydict_in_str.lower())
print(mydict_lowercase)
深居我梦 2024-07-24 02:56:47

在Python 3中:

d = dict()
d = {k.casefold(): v for k, v in d.items()}

In Python 3:

d = dict()
d = {k.casefold(): v for k, v in d.items()}
你在我安 2024-07-24 02:56:47

如果提供的字典有多种类型的键/值(数字、字符串等); 然后使用以下解决方案。

例如; 如果您有一个名为 mydict 的字典,如下所示

mydict = {"FName":"John","LName":"Doe",007:true}

在 Python 2.x 中

dict((k.lower() if isinstance(k, basestring) else k, v.lower() if isinstance(v, basestring) else v) for k,v in mydict.iteritems())

在 Python 3.x 中

dict((k.lower() if isinstance(k, str) else k, v.lower() if isinstance(v, str) else v) for k,v in mydict.iteritems())

注意: 这对于单维字典效果很好

If the dictionary supplied have multiple type of key/values(numeric, string etc.); then use the following solution.

For example; if you have a dictionary named mydict as shown below

mydict = {"FName":"John","LName":"Doe",007:true}

In Python 2.x

dict((k.lower() if isinstance(k, basestring) else k, v.lower() if isinstance(v, basestring) else v) for k,v in mydict.iteritems())

In Python 3.x

dict((k.lower() if isinstance(k, str) else k, v.lower() if isinstance(v, str) else v) for k,v in mydict.iteritems())

Note: this works good on single dimensional dictionaries

情深如许 2024-07-24 02:56:47

我这么晚才回答 - 因为问题被标记为 Python
因此,我们需要针对 Python 2.xPython 3.x 提供解决方案,并处理非字符串键的情况。

Python 2.x - 使用字典理解

{k.lower() if isinstance(k, basestring) else k: v.lower() if isinstance(v, basestring) else v for k,v in yourDict.iteritems()}

演示

>>> yourDict = {"Domain":"WORKGROUP", "Name": "CA-LTP-JOHN", 111: 'OK', "Is_ADServer": 0, "Is_ConnectionBroker": 0, "Domain_Pingable": 0}
>>> {k.lower() if isinstance(k, basestring) else k: v.lower() if isinstance(v, basestring) else v for k,v in yourDict.iteritems()}
{'domain': 'workgroup', 'name': 'ca-ltp-john', 'is_adserver': 0, 'is_connectionbroker': 0, 111: 'ok', 'domain_pingable': 0}

Python 3.x - Python 3 中没有 iteritems() .x

{k.lower() if isinstance(k, str) else k: v.lower() if isinstance(v, str) else v for k,v in yourDict.items()}

演示

>>> dict((k.lower() if isinstance(k, basestring) else k, v.lower() if isinstance(v, basestring) else v) for k,v in yourDict.iteritems())
Traceback (most recent call last):
  File "python", line 1, in <module>
AttributeError: 'dict' object has no attribute 'iteritems'
>>> {k.lower() if isinstance(k, str) else k: v.lower() if isinstance(v, str) else v for k,v in yourDict.items()}
>>> {'domain': 'workgroup', 'name': 'ca-ltp-john', 111: 'ok', 'is_adserver': 0, 'is_connectionbroker': 0, 'domain_pingable': 0}

I am answering this late - as the question is tagged Python.
Hence answering with a solution for both Python 2.x and Python 3.x, and also handling the case of non-string keys.

Python 2.x - using dictionary comprehension

{k.lower() if isinstance(k, basestring) else k: v.lower() if isinstance(v, basestring) else v for k,v in yourDict.iteritems()}

Demo:

>>> yourDict = {"Domain":"WORKGROUP", "Name": "CA-LTP-JOHN", 111: 'OK', "Is_ADServer": 0, "Is_ConnectionBroker": 0, "Domain_Pingable": 0}
>>> {k.lower() if isinstance(k, basestring) else k: v.lower() if isinstance(v, basestring) else v for k,v in yourDict.iteritems()}
{'domain': 'workgroup', 'name': 'ca-ltp-john', 'is_adserver': 0, 'is_connectionbroker': 0, 111: 'ok', 'domain_pingable': 0}

Python 3.x - no iteritems() in Python 3.x

{k.lower() if isinstance(k, str) else k: v.lower() if isinstance(v, str) else v for k,v in yourDict.items()}

Demo:

>>> dict((k.lower() if isinstance(k, basestring) else k, v.lower() if isinstance(v, basestring) else v) for k,v in yourDict.iteritems())
Traceback (most recent call last):
  File "python", line 1, in <module>
AttributeError: 'dict' object has no attribute 'iteritems'
>>> {k.lower() if isinstance(k, str) else k: v.lower() if isinstance(v, str) else v for k,v in yourDict.items()}
>>> {'domain': 'workgroup', 'name': 'ca-ltp-john', 111: 'ok', 'is_adserver': 0, 'is_connectionbroker': 0, 'domain_pingable': 0}
没企图 2024-07-24 02:56:47

喜欢使用多级函数的方式,这是我将按键小写的方式

def to_lower(dictionary):

    def try_iterate(k):
        return lower_by_level(k) if isinstance(k, dict) else k

    def try_lower(k):
        return k.lower() if isinstance(k, str) else k

    def lower_by_level(data):
        return dict((try_lower(k), try_iterate(v)) for k, v in data.items())

    return lower_by_level(dictionary)

Love the way you can use multilevel functions, here's my way of lowercase-ing the keys

def to_lower(dictionary):

    def try_iterate(k):
        return lower_by_level(k) if isinstance(k, dict) else k

    def try_lower(k):
        return k.lower() if isinstance(k, str) else k

    def lower_by_level(data):
        return dict((try_lower(k), try_iterate(v)) for k, v in data.items())

    return lower_by_level(dictionary)
云朵有点甜 2024-07-24 02:56:47

Python 3 中,您可以执行以下操作:

dict((k.lower(), v.lower()) for k,v in {'Key':'Value'}.items())

Python 2 中,只需将 .items() 替换为 .iteritems()

dict((k.lower(), v.lower()) for k,v in {'Key':'Value'}.iteritems())

In Python 3 you can do:

dict((k.lower(), v.lower()) for k,v in {'Key':'Value'}.items())

In Python 2 just substitute .items() for .iteritems():

dict((k.lower(), v.lower()) for k,v in {'Key':'Value'}.iteritems())
入怼 2024-07-24 02:56:47

一个选项是从 UserDict 进行子类型化,这样插入的所有数据都将具有小写键,并且您无需在访问时关心小写:

from collections import UserDict
from typing import Any

class InsensitiveCaseDict(UserDict):
    def __getitem__(self, key: Any) -> Any:
        if type(key) is str:
            return super().__getitem__(key.lower())
        return super().__getitem__(key)

    def __setitem__(self, key: Any, item: Any) -> Any:
        if type(key) is str:
            self.data[key.lower()] = item
            return
        self.data[key] = item

并且您可以转换原始字典:

insensitive_case_dict = InsensitiveCaseDict(my_original_dict)

An option is to subtype from UserDict, and that way all data inserted will have lower case key and you don't need to care about to lower case at access time:

from collections import UserDict
from typing import Any

class InsensitiveCaseDict(UserDict):
    def __getitem__(self, key: Any) -> Any:
        if type(key) is str:
            return super().__getitem__(key.lower())
        return super().__getitem__(key)

    def __setitem__(self, key: Any, item: Any) -> Any:
        if type(key) is str:
            self.data[key.lower()] = item
            return
        self.data[key] = item

And you can convert your original dict:

insensitive_case_dict = InsensitiveCaseDict(my_original_dict)
梦情居士 2024-07-24 02:56:47

除了 @vldbnc 答案之外,如果您只想仅在 python 3.x 中的嵌套字典中小写键

def _dict_keys_lowercase(obj):
    """ Make dictionary lowercase """
    if isinstance(obj, dict):
        return {k.lower():_dict_keys_lowercase(v) for k, v in obj.items()}
    else:
        return obj

In addition to @vldbnc answer, if you only want to lowercase the keys only in a nested dict in python 3.x

def _dict_keys_lowercase(obj):
    """ Make dictionary lowercase """
    if isinstance(obj, dict):
        return {k.lower():_dict_keys_lowercase(v) for k, v in obj.items()}
    else:
        return obj
这个俗人 2024-07-24 02:56:47
def convert_to_lower_case(data):
    if type(data) is dict:
        for k, v in data.iteritems():
            if type(v) is str:
                data[k] = v.lower()
            elif type(v) is list:
                data[k] = [x.lower() for x in v]
            elif type(v) is dict:
                data[k] = convert_to_lower_case(v)
    return data
def convert_to_lower_case(data):
    if type(data) is dict:
        for k, v in data.iteritems():
            if type(v) is str:
                data[k] = v.lower()
            elif type(v) is list:
                data[k] = [x.lower() for x in v]
            elif type(v) is dict:
                data[k] = convert_to_lower_case(v)
    return data
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文