Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to check Python multi-level dictionary

Tags:

python

Currently I am using the following method, assume dictionary

data[a][b][c]

I use:

if "a" in data and "b" in data["a"] and "c" in data["a"]["b"]:
  ...

Are there any better way?

like image 806
Ryan Avatar asked Dec 26 '13 14:12

Ryan


2 Answers

You can wrap it in a try/except block

try:
    x = data[a][b][c]
    ...do stuff in your "if" clause
except KeyError:
    ...do stuff in your "else" clause
like image 121
tdelaney Avatar answered Oct 06 '22 23:10

tdelaney


I would typically use the pattern

foo = data.get("a",{}).get("b",{}).get("c",False)
if foo:
...

This requires that the nesting is always the same depth and that data["a"]["b"]["c"] is not "falsy".

like image 24
colcarroll Avatar answered Oct 06 '22 23:10

colcarroll