创建字典时设置字典的值
Setting values of a dictionary while creating it
我试图根据字典的键设置值,同时创建字典本身。
我可以通过额外的步骤来完成,但是有没有办法做到以下几点:
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',
}
使用理解创建字典:
>>> {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'}
我试图根据字典的键设置值,同时创建字典本身。
我可以通过额外的步骤来完成,但是有没有办法做到以下几点:
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',
}
使用理解创建字典:
>>> {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'}