Dictionary to lowercase in Python

前端 未结 12 1137
无人共我
无人共我 2020-12-03 02:10

I wish to do this but for a dictionary:

\"My string\".lower()

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

12条回答
  •  囚心锁ツ
    2020-12-03 02:58

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

提交回复
热议问题