Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: getting sub-dicts in dicts dynamically?

Say I want to write a function which will return an arbitrary value from a dict, like: mydict['foo']['bar']['baz'], or return an empty string if it doesn't. However, I don't know if mydict['foo'] will necessarily exist, let alone mydict['foo']['bar']['baz'].

I'd like to do something like:

safe_nested(dict, element):
  try:
    return dict[element]
  except KeyError:
    return ''

But I don't know how to approach writing code that will accept the lookup path in the function. I started going down the route of accepting a period-separated string (like foo.bar.baz) so this function could recursively try to get the next sub-dict, but this didn't feel very Pythonic. I'm wondering if there's a way to pass in both the dict (mydict) and the sub-structure I'm interested in (['foo']['bar']['baz']), and have the function try to access this or return an empty string if it encounters a KeyError.

Am I going about this in the right way?

like image 894
Christopher Armstrong Avatar asked Feb 24 '26 11:02

Christopher Armstrong


1 Answers

You should use the standard defaultdict: https://docs.python.org/2/library/collections.html#collections.defaultdict

For how to nest them, see: defaultdict of defaultdict, nested or Multiple levels of 'collection.defaultdict' in Python

I think this does what you want:

from collections import defaultdict
mydict = defaultdict(lambda: defaultdict(lambda: defaultdict(str)))
like image 104
John Zwinck Avatar answered Feb 26 '26 02:02

John Zwinck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!