【问题标题】:Converting all values in a list of dictionaries to lowercase in Python 3在 Python 3 中将字典列表中的所有值转换为小写
【发布时间】:2013-11-12 16:12:29
【问题描述】:

我知道这很简单,但我想不通。 我想将一个看起来像下面这样的字典列表中的所有值转换为小写:

{'John greased ': ['Axle', 'wheel', 'wheels', 'wheel', 'enGine', ''], 
 'Maria testa': ['teste', 'teste', '', '', '', ''], 
 'Paul alleged ': ['truth', 'crime', 'facts', 'infidelity', 'incident', ''], 
 'Tracy freed ': ['animals', 'fish', 'slaves', 'slaves', 'slaves', 'pizza'], 
 'Lisa plowed ': ['field', 'Field', 'FIELD', 'bola', '', '']}

我尝试使用:

low = {k.lower():v.lower() for k, v in result.items()}
print(low)

但这行不通。关于如何解决这个问题的任何建议?非常感谢!

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    你的值是列表,所以添加一个列表理解:

    {k.lower(): [i.lower() for i in v] for k, v in result.items()}
    

    演示:

    >>> result = {'John greased ': ['Axle', 'wheel', 'wheels', 'wheel', 'enGine', ''], 
    ...  'Maria testa': ['teste', 'teste', '', '', '', ''], 
    ...  'Paul alleged ': ['truth', 'crime', 'facts', 'infidelity', 'incident', ''], 
    ...  'Tracy freed ': ['animals', 'fish', 'slaves', 'slaves', 'slaves', 'pizza'], 
    ...  'Lisa plowed ': ['field', 'Field', 'FIELD', 'bola', '', '']}
    >>> {k.lower(): [i.lower() for i in v] for k, v in result.items()}
    {'lisa plowed ': ['field', 'field', 'field', 'bola', '', ''], 'tracy freed ': ['animals', 'fish', 'slaves', 'slaves', 'slaves', 'pizza'], 'paul alleged ': ['truth', 'crime', 'facts', 'infidelity', 'incident', ''], 'maria testa': ['teste', 'teste', '', '', '', ''], 'john greased ': ['axle', 'wheel', 'wheels', 'wheel', 'engine', '']}
    >>> from pprint import pprint
    >>> pprint({k.lower(): [i.lower() for i in v] for k, v in result.items()})
    {'john greased ': ['axle', 'wheel', 'wheels', 'wheel', 'engine', ''],
     'lisa plowed ': ['field', 'field', 'field', 'bola', '', ''],
     'maria testa': ['teste', 'teste', '', '', '', ''],
     'paul alleged ': ['truth', 'crime', 'facts', 'infidelity', 'incident', ''],
     'tracy freed ': ['animals', 'fish', 'slaves', 'slaves', 'slaves', 'pizza']}
    

    【讨论】:

    • 完美。现在我明白了!非常感谢!
    猜你喜欢
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 2022-11-14
    相关资源
    最近更新 更多