Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแปลง Python Dictionary Keys/Values เป็นตัวพิมพ์เล็ก

คุณสามารถแปลง Python dictionary keys/values เป็นตัวพิมพ์เล็กได้โดยการวนลูปผ่านพวกมันและสร้าง dict ใหม่จากคีย์และค่า ตัวอย่างเช่น:

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