【问题标题】:How to conditionally replace a key using dict comprehension如何使用字典理解有条件地替换键
【发布时间】:2019-04-16 18:16:46
【问题描述】:

我有一本字典

d={'user': 'bala', 'password': 'pass', 'filetype': 'as-parquetfile'}

所有键都应以-- 为前缀,但filetype 应替换为-- 以获得

{'--user': 'bala', '--password': 'pass', '--': 'as-parquetfile'}

如果我执行以下操作,我会收到语法错误。

{'--'+k:v if k!='filetype' else '--':v for (k,v) in d.items()}

【问题讨论】:

    标签: python dictionary-comprehension


    【解决方案1】:

    dict 推导式的key: value 部分没有表达式,因此不能直接使用三元运算符。你可以这样做:

    {('--'+k if k!='filetype' else '--'): v for (k,v) in d.items()}
    

    【讨论】:

    • @pault 您会这么认为,但请看问题中的要求。
    【解决方案2】:

    我喜欢用一种肮脏的方式:

    d = {'user': 'bala', 'password': 'pass', 'filetype': 'as-parquetfile'}
    d = {"--" + (k, "")[k=="filetype"]: v for k, v in d.items()}
    d
    >>> {'--': 'as-parquetfile', '--password': 'pass', '--user': 'bala'}
    

    【讨论】:

    • 使用 True 和 False 作为元组的索引值很聪明,但可读性较差
    猜你喜欢
    • 2015-09-26
    • 1970-01-01
    • 2022-11-23
    • 2014-06-18
    • 2013-07-09
    • 2020-05-28
    • 1970-01-01
    • 1970-01-01
    • 2019-12-09
    相关资源
    最近更新 更多