【问题标题】:Setting values of a dictionary while creating it在创建字典时设置字典的值
【发布时间】:2021-09-01 14:53:22
【问题描述】:

我试图根据字典的键设置值,同时创建字典本身。

我可以通过一个额外的步骤来做到这一点,但有没有办法做到以下几点:

dictionary = {
    'a': 'Key of this = ' + dictionary.key(),
    'b': 'Key of this = ' + dictionary.key(),
    'c': 'Key of this = ' + dictionary.key(),
}

预期的结果是:

>>>dictionary
{
    'a': 'Key of this = a',
    'b': 'Key of this = b',
    'c': 'Key of this = c',
}

【问题讨论】:

    标签: python dictionary key


    【解决方案1】:

    使用推导式创建字典:

    >>> {key: f"Key of this = {key}" for key in ('a', 'b', 'c')}
    {'a': 'Key of this = a', 'b': 'Key of this = b', 'c': 'Key of this = c'}
    

    【讨论】:

    • 工作,谢谢,12分钟后我就能接受了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 1970-01-01
    • 2019-03-03
    • 2019-08-07
    • 2021-10-25
    相关资源
    最近更新 更多