Home > OS >  python: how to reduce to one-liner:
python: how to reduce to one-liner:

Time:12-20

How do I write the following in minimum lines?

if a in dict:
   if b in dict[a]:
       if c in dict[a][b]:
            if d in dict[a][b][c]:
                 print("Value = ", dict[a][b][c][d])

Using python 3.10

CodePudding user response:

It is recommended to use a try/except block instead of checking if each key is present. In your case I would go for:

try:
    print("Value = ", dict[a][b][c][d])
except KeyError as e:
    print(f"Missing key: {e}")

CodePudding user response:

You can combine all of them in one line using AND operator:

if a in dct and b in dct[a] and c in dct[a][b] and d in dct[a][b][c]:
    print("Value = ", dct[a][b][c][d])

But as the other answer says, it is best practice to use try/except.

  • Related