Dictionary to lowercase in Python

前端 未结 12 1089
无人共我
无人共我 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条回答
  •  -上瘾入骨i
    2020-12-03 03:08

    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)
    

提交回复
热议问题