Is there a compact way to unpack some values from a dictionary in Python?

Viewed 62

I encounter the current situation many times in my codes. I define a dictionary.

params = {
    'color': 'green',
    'xlim': (0, 250),
    'ylim': (0, 10),
    'ylabel': 'the label',
    'xlabel': 'time'
}

Then, inside the definition of some functions, I unpack some values from a dictionary like the above into a tuple

color, ylim, ylabel, xlabel = params['color'], params['ylim'], params['ylabel'], params['xlabel']   

I imagine there should be a better way to do this unpacking. So I tried the following

color, ylim, ylabel, xlabel = params['color','ylim','ylabel','xlabel']

but it gives an error.

KeyError: ('color', 'ylim', 'ylabel', 'xlabel')

So, my questions are

  • Is there a more compact way to unpack some values from a dictionary in Python?
  • Is unpacking a dictionary like this a bad practice?
1 Answers

You could do something like this:

params = {
    'color': 'green',
    'xlim': (0, 250),
    'ylim': (0, 10),
    'ylabel': 'the label',
    'xlabel': 'time'
}
color, ylim, ylabel, xlabel = (params[x] for x in ('color', 'ylim', 'ylabel', 'xlabel'))
print(color)

Out:

green
Related