如何將 Python 字典鍵值轉換為小寫?


你可以透過遍歷並透過鍵值建立一個新詞典來將 Python 字典鍵/值轉換為小寫。例如:

def lower_dict(d):
   new_dict = dict((k.lower(), v.lower()) for k, v in d.items())
   return new_dict
a = {'Foo': "Hello", 'Bar': "World"}
print(lower_dict(a))

這將給出會顯示

{'foo': 'hello', 'bar': 'world'}

如果你僅想將鍵轉換為小寫,則可以僅對其呼叫 lower。例如:

def lower_dict(d):
   new_dict = dict((k.lower(), v) for k, v in d.items())
   return new_dict
a = {'Foo': "Hello", 'Bar': "World"}
print(lower_dict(a))

這將給出會顯示

{'foo': 'Hello', 'bar': 'World'}

更新於:2020 年 6 月 17 日

4K+ 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.