2

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?
wjandrea
  • 28,235
  • 9
  • 60
  • 81
sfx
  • 103
  • 9
  • Thanks for letting me know about `**`. I am reading about it to see if it can help. – sfx Nov 20 '21 at 20:54

1 Answers1

1

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
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47
  • Yes, list (tuple?) comprehensions! I forgot about them. What do you think about my second question? – sfx Nov 20 '21 at 20:57
  • 1
    @sfx This is actually a [generator expression](https://docs.python.org/3/reference/expressions.html#generator-expressions). – wjandrea Nov 20 '21 at 20:59
  • It's fine. In case you heavily use dictionary values, there is a lot of overhead typing. Sometimes I wish an (additional) 'dot notation' for dicts. Just `params.color`. – Maurice Meyer Nov 20 '21 at 21:02
  • @MauriceMeyer I found [this answer](https://stackoverflow.com/a/16279578/8142021) about the 'dot notation'. It might be better indeed. – sfx Nov 20 '21 at 21:07
  • @sfx: Yes for flat dicts this is fine, but not for nested ones. – Maurice Meyer Nov 20 '21 at 21:12