I have a class that inherits the dict
object.
my_subclassed_dict = SubclassedDictionary({
"id": {"value1": 144
"value2": "steve",
"more" {"id": 114}
},
"attributes": "random"
})
On initialization of SubclassedDictionary
, I would like paths generated which match a certain condition.
Hypothetically, if I was to make this condition, 'index all numbers above 100' This could perhaps then access my_subclassed_dict.get_paths()
, which would then return some kind of structure resembling this:
[
['id', 'value1'],
['id', 'more', 'id',]
]
In short, how can I subclass dict
which generates paths for keys matching a certain condition, on instantiation?
EDIT
Since someone asked for an example implementation. However the problem with this is that it doesn't handle nested dictionaries.
class SubclassedDictionary(dict):
paths = []
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs) # use the free update to set keys
def update(self, *args, **kwargs):
temp = args[0]
for key, value in temp.items():
if isinstance(value, int):
if value > 100:
self.paths.append(key)
super(SubclassedDictionary, self).update(*args, **kwargs)
dictionary = {
"value1": 333,
"v2": 99,
"v2": 129,
"v3": 30,
"nested": {
"nested_value" 1000
}
}
new_dict = SubclassedDictionary(dictionary)
print(new_dict.paths) # outputs: ['v2','value1']
If it did work as intended.
print(new_dict.paths)
Would output
[
['v2'],
['value1'],
['nested', 'nested_value']
]