如何在列表理解中将字典值转换为小写?

Mah*_*a M 1 python dictionary list lowercase python-3.x

我有一个字典清单,

list_dict = [{'name':'Rita' , 'customer_id': 'A12B1', 'city': 'Chennai'}, 
             {'name':'Sita' , 'customer_id': 'A61B8', 'city': 'Salem'}]
Run Code Online (Sandbox Code Playgroud)

我需要得到结果,

list_dict = [{'name':'rita' , 'customer_id': 'a12b1', 'city': 'chennai'}, 
             {'name':'sita' , 'customer_id': 'a61b8', 'city': 'salem'}]
Run Code Online (Sandbox Code Playgroud)

我尝试过

new_list = []
for index in range(len(list_dict)):
    new_dict = {}
    for key,val in list_dict[index].items():
        new_dict[key] = str(val).lower()
new_list.append(new_dict)
Run Code Online (Sandbox Code Playgroud)

如何使用列表理解获得相同的结果?

lmi*_*asf 5

我认为这可以解决您的问题:

[{ key: str(value).lower() for key, value in e.items() } for e in list_dict ]
Run Code Online (Sandbox Code Playgroud)

基本上,您必须使用包含dict理解的列表理解。

  • @MahamuthaM,我想您应该在问题中提及这一点,以免造成混淆。否则,我最初提供的代码就足够了。 (2认同)