I wrote a function to convert all keys in a dictionary to lowercase:
def lower_dict_keys(some_dict):
"""Convert all keys to lowercase"""
result = {}
for key, value in some_dict.items():
if type(key) == str:
result[key.lower()] = value
else:
result[key] = value
return result
So far so good. Then I thought, hm, this would be more elegant in a dictionary comprehension, so this is what I came up with:
def lower_dict_keys2(some_dict):
return {key.lower(): value for key, value in some_dict.items() if type(key) == str}
This only works if all keys are strings. I there are numeric keys, they get dropped:
d1 = {'A':'foo', 'b':'bar', 1:'zip'}
print(lower_dict_keys(d1))
>>>{'a': 'foo', 'b': 'bar', 1: 'zip'}
print(lower_dict_keys2(d1))
>>>{'a': 'foo', 'b': 'bar'}
So my question is: is it possible to write this function as a dictionary comprehension?