1

I have a python dictionary like so:

{
"addressLineOne": self.ADDRESS_1,
"addressType": "RESIDENTIAL",
"city": self.CITY,
"countryCode": "USA",
"email": self.EMAIL,
"firstName": self.FIRST_NAME,
"state": self.STATE
}

I want some values to be condition the way I'm currently doing it is like so:

if self.login:
    data = {"addressLineOne": self.ADDRESS_1,
            "addressType": "RESIDENTIAL",
            "city": self.CITY,
            "countryCode": "USA",
            "state": self.STATE}
else:
    data = {"addressLineOne": self.ADDRESS_1,
            "addressType": "RESIDENTIAL",
            "city": self.CITY,
            "countryCode": "USA",
            "email": self.EMAIL,
            "firstName": self.FIRST_NAME,
            "state": self.STATE}

Is there a neater/tidier way of doing this so I don't need to write the dictionary twice, for example including an if/else statement within the dictionary?

GAP2002
  • 870
  • 4
  • 20

2 Answers2

10

For your specific case, the else part just adds keys. So initialize the dict with the shared ones, and add the extras with a condition. Something like:

data = {"addressLineOne": self.ADDRESS_1,
        "addressType": "RESIDENTIAL",
        "city": self.CITY,
        "countryCode": "USA",
        "state": self.STATE}

if not self.login:
    data.update({"email": self.EMAIL,
                 "firstName": self.FIRST_NAME})
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • Definitely, a valid answer, and no reason to not use it although I prefer the accepted answer as it's just nicer to do it upon the creation of the dictionary. Thanks for the input though. – GAP2002 Dec 17 '20 at 15:48
  • @GAP2002 no problem, happy to help. Just remember that as the [Zen of Python](https://www.python.org/dev/peps/pep-0020/) states: *Readability counts* ;) – Tomerikoo Dec 17 '20 at 16:01
7

I have occasionally written things like

data = {
    'this': that,
    'foo': bar,
    **({'cond1': 17, cond2: 'xyzzy'} if new_moon() else {})
}

but I'll leave it to someone else to decide whether it makes sense...

Ture Pålsson
  • 6,088
  • 2
  • 12
  • 15