【问题标题】:Python: dict comprehension from a list with key and value being strings?Python:从键和值是字符串的列表中理解字典?
【发布时间】:2013-04-07 18:10:07
【问题描述】:

我想把列表('a','b','c')变成{'1':'a','2':'b','3':'c'}

 d = {key: value for key, value in targets}

以整数形式返回键,我需要将其存储为字符串,以便我可以将字符串附加到每个键,这样最终我会得到

{'column1','a','column2','b','column3'}

【问题讨论】:

    标签: python dictionary dictionary-comprehension


    【解决方案1】:

    只需将密钥投射到str()enumerate()

    d = {str(i): value for i, value in enumerate(targets)}
    

    如果您需要在键前添加字符串,请使用格式化:

    d = {'column{}'.format(i): value for i, value in enumerate(targets)}
    

    dict 推导式中的键和值表达式就是这样,python 表达式。

    【讨论】:

    • 太棒了,在Java中根本无法优雅地做到这一点
    • @KimJongWoo:在 Python 2.7 中添加了 dict 理解语法;在早期版本中使用dict(('column{}'.format(i), value) for i, value in enumerate(targets))
    • 是的,我最终改用了 dict()。然而,它非常强大。
    • d = {'column{}'.format(i): value for i, value in enumerate(targets)} 我无法跟踪 i 的管理方式 - 请帮助!
    猜你喜欢
    • 2020-01-24
    • 2021-01-02
    • 2020-09-04
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 2011-03-14
    • 2021-03-12
    • 1970-01-01
    相关资源
    最近更新 更多