Search code examples
pythondictionarykey

Setting values of a dictionary while creating it


I was trying to set the values according to the keys of the dictionary, while creating the dictionary itself.

I can do it with an additional step, but is there a way to do the following:

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

Expected outcome would be then:

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

Solution

  • Create the dictionary using a comprehension:

    >>> {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'}