I try to find a better/nicer/cleaner way to get selected values of a data structure and add them to a new data structure, in this case a class.
I have an object/class where I want to put the selected data into:
class foo:
def __init__:
self.name = None
self.server = None
self.id = None
self.foo = None
Now I get the data through json which I dump into a regular data structure (just mentioning in case there is a json hack somehow).
The data could be be in one case
data = {
'id': '1234',
'x': {
'y': 'asdfasdf',
},
'a': {
'b': 'foo'
}
}
For such a case I can easily assign it in a function via
self.id = data['id'],
self.foo = data['x']['y']
self.name = data['a']['b']
The challenge starts when the data I get doesn't have all the values defined.
In the following case data['x']
isn't defined and data['a']['b']
doesn't exist, either.
data = {
'id': '2345',
'a': {
'X': 'bar'
}
}
As result, with the second input data I can't use a simple
self.id = data['id'],
self.foo = data['x']['y']
self.name = data['a']['b']
Of course I can do all these test like
if 'x' data and 'y' in data['x']
self.foo = data['x']['y']
if 'b' in data['a']: # assuming data['a'] always exists
self.name = data['a']['b']
Now what I am looking for is a slick, much shorter & nicer to read option to process the input data even if a value isn't defined. Without the requirement to check if a value exist. Assigning it if it exists and ignoring it (or setting it to None
) if it doesn't exists.
Something that scales to much more variables and depth as the two values provided in the above example.
One option I thought about was maybe create a mapping and then do a function that does all the checks based on the mapping. This also comes with some own error checking logic. Like:
mappings = {
'id': 'id',
'foo': 'x.y.',
'name': 'a.b'
}
data_input = {
'id': '2345',
'a': {
'X': 'bar'
}
}
map_function(mappings, data_input, class_object)
# Pseudo code, could contain syntax errors
# Probably also a lot of improvements possible like doing the depth recursively.
# This is just a big picture logic POC
def map_function(mappings, data_input, class_object):
for mapping in mappings:
for case in mappings[mapping].split('.'):
if case in data_input:
if type(data_input[case]) in ['str', 'int', 'NoneType']):
# need to figure out how to use the value here
# and don't set it to `mapping`
class_object.mapping = data_input[case]
else:
# go down another layer
# A recursion function execution would work best her
...
else:
continue