you can write your own helper class to make your code clear.
dict_helper.py:
from collections import UserDict
# reference: https://realpython.com/inherit-python-dict/
class DictHelper(UserDict):
"""
reference: https://mcmap.net/q/42018/-elegant-way-to-check-if-a-nested-key-exists-in-a-dict
"""
def has_key(self, path: str | list):
keys = path.split('.') if isinstance(path, str) else path
val = self.data
for key in keys:
if not key in val:
return False
else:
val = val[key]
return True
# Throwing in this approach for nested get for the heck of it...
def get_key(self, path: str | list, default=None):
keys = path.split('.') if isinstance(path, str) else path
val = self.data
for key in keys:
if key in val:
val = val[key]
else:
return default
return val
def set_key(self, path: str | list, value):
keys = path.split('.') if isinstance(path, str) else path
val = self.data
for key in keys[:-1]:
val.setdefault(key, {})
val = val[key]
val[keys[-1]] = value
main.py:
from dict_helper import DictHelper
# way1
d = DictHelper({})
d.set_key(['person', 'address', 'city'], 'New York')
print(d)
# or way2
d = DictHelper({})
d.set_key('person.address.city', 'New York')
print(d)
# both way has the same result
# output={'person': {'address': {'city': 'New York'}}}
you can also use your own helper functions and helper classes in future projects.
new update 17 Feb 2024:
there is a very good library exists that can handle your class easier. just install it by below command:
pip install "python-benedict[all or io for this project]"
now you can define this class very easily:
from collections import UserDict
from benedict import benedict
class DictHelper(UserDict):
def __init__(self, d: dict = None):
super().__init__(d)
self.d = benedict().from_json(self.data)
@staticmethod
def __keypath__(path: str | list):
return path if isinstance(path, str) else '.'.join(path)
def has_key(self, path: str | list):
return self.__keypath__(path) in self.d
def get_key(self, path: str | list):
return self.d[self.__keypath__(path)]
def set_key(self, path: str | list, value=None):
self.d[self.__keypath__(path)] = value
dict[x][y][z] = value
? Where do you getvalue
from? What's with the weird format? – Inexpungibled[tuple(da_list)] = value
– Raynold