0

Is there a more elegant/shorter way to conditionally add a key-value pair to a dictionary in python than this:

extra = {'foo': 'bar'}
if something is True:
   extra['some'] = 'thing'
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
pasql
  • 3,815
  • 5
  • 23
  • 33
  • 7
    This is elegant enough to me. – yangjie Aug 28 '15 at 14:12
  • 6
    `is True` is redundant, otherwise, just fine. – bereal Aug 28 '15 at 14:16
  • @bereal: Omitting `is True` changes the meaning significantly. Dunno if it is intentional or not, but it is certainly not redundant without knowing more. –  Aug 28 '15 at 14:27
  • @doublep if it changes the semantics, it's likely un-pythonic style because of type-checking vs duck-typing. – bereal Aug 28 '15 at 14:30
  • The first line is the definition of the dictionary itself. So you only have two lines, one of which checks if a condition is true. How is `extra['some'] = 'thing'` not elegant/short enough? – Markus Meskanen Aug 28 '15 at 14:48
  • @doublep: Sure, it changes the meaning, but most of the time when a new Python programmer writes `if something is True:` they _really_ should be writing `if something:` instead. – PM 2Ring Aug 28 '15 at 14:50
  • @PM2Ring: Or maybe `something` is a list of values to accept, while special-cased `True` means "everything is accepted". –  Aug 28 '15 at 14:55
  • @doublep: Maybe I don't get what you mean. If `something` is a list then `something is True` can never be true! `something is True` can only be true if the name `something` is bound to the `bool` object `True`. – PM 2Ring Aug 28 '15 at 15:01
  • Could you give an example of how you would like it to look, even if it's not valid Python? That way we can know what you're going for. – Cody Piersall Aug 28 '15 at 15:23
  • @PM2Ring: E.g. "This attribute can be either a list of additional facets to install or special value `True` meaning 'install all you have'. `None` or an empty list mean there will be no additional facets." –  Aug 28 '15 at 15:29
  • @doublep; Yeah, ok. But in that case it'd be part of an if..elif.. construction, so it'd be obvious why the code is explicitly testing if `something is True`. – PM 2Ring Aug 28 '15 at 15:41

1 Answers1

0

How about using update()

extra = {'foo': 'bar'} extra.update({'some': 'thing'})

  • Update's a nice method, especially for adding multiple key-value pairs, but your code _unconditionally_ adds the new key-value pair, and the crux of the question is how to do it _conditionally_, in an efficient way. I guess you could do `extra.update({'some': 'thing'} if something else {})`, but it's probably _much_ less efficient than the code in the OP. :) – PM 2Ring Aug 28 '15 at 15:48