Search code examples
pythondictionaryreturn

Return key, value and assign to dictionary in one line in Python


I have a function which executes a job and return job id and whether it was successfull. Then I need to store these results in a dict. Currently I do this:

jobs_results = {}

...

job_id, job_result = execute_function()
jobs_results[job_id] = job_result

However, I was wondering if there is a way to turn these two lines into an oneliner, or if this is the Pythonic way to do this?


Solution

  • You can update your dictionary with a tuple of tuples,

    jobs_results.update((execute_function(),))
    

    or just assign it as a tuple of tuples

    job_results = dict((execute_function(),))
    

    I'd prefer your current approach though as its clearer