【问题标题】:How to convert the dictionary values to lower case in list comprehension?如何在列表理解中将字典值转换为小写?
【发布时间】:2019-09-06 03:23:37
【问题描述】:

我有一个字典列表,

list_dict = [{'name':'Rita' , 'customer_id': 'A12B1', 'city': 'Chennai'}, 
             {'name':'Sita' , 'customer_id': 'A61B8', 'city': 'Salem'}]

我需要得到结果,

list_dict = [{'name':'rita' , 'customer_id': 'a12b1', 'city': 'chennai'}, 
             {'name':'sita' , 'customer_id': 'a61b8', 'city': 'salem'}]

我试过了,

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)

如何使用列表推导获得相同的结果?

【问题讨论】:

    标签: python python-3.x list dictionary lowercase


    【解决方案1】:

    我认为这会解决你的问题:

    [{ key: str(value).lower() for key, value in e.items() } for e in list_dict ]
    

    基本上,您必须使用包含字典推导的列表推导。

    【讨论】:

    • 转换为str 似乎没有必要,至少在示例数据中是这样。
    • @AdamSmith,我同意你的观点,但问题的作者进行了编辑。
    • @Adam Smith,如果假设值是整数,那么这不起作用 => [{ key: value.lower() for key, value in e.items() } for e in list_dict ]
    • @MahamuthaM,我认为您应该在问题中提及这一点,以避免这种混淆。不然我原来提供的代码就够了。
    • @MahamuthaM 是的,但在这种情况下,您的样本数据不是很有代表性:) 没关系,只是让读者感到困惑。
    【解决方案2】:
    list_dict = [ { k:v.lower() for k,v in d.items() } for d in list_dict ]
    

    【讨论】:

      【解决方案3】:

      基本上,您必须使用包含字典推导的列表推导。

      [ { k:v.lower() for k,v in s.items() } for s in list_dict ]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-11
        相关资源
        最近更新 更多