I’ve a flat dict with entities. Each entity can have a parent. I’d like to recursively build each entity, considering the parent values.
Logic:
- Each entity inherits defaults from its parent (e.g.
is_mammal
) - Each entity can overwrite the defaults of its parent (e.g.
age
) - Each entity can add new attributes (e.g.
hobby
)
I’m struggling to get it done. Help is appreciated, thanks!
JavaScript
x
23
23
1
entities = {
2
'human': {
3
'is_mammal': True,
4
'age': None,
5
},
6
'man': {
7
'parent': 'human',
8
'gender': 'male',
9
},
10
'john': {
11
'parent': 'man',
12
'age': 20,
13
'hobby': 'football',
14
}
15
};
16
17
def get_character(key):
18
# ... recursive magic with entities ...
19
return entity
20
21
john = get_character('john')
22
print(john)
23
Expected output:
JavaScript
1
8
1
{
2
'is_mammal': True, # inherited from human
3
'gender': 'male' # inherited from man
4
'parent': 'man',
5
'age': 20, # overwritten
6
'hobby': 'football', # added
7
}
8
Advertisement
Answer
JavaScript
1
8
1
def get_character(entities, key):
2
try:
3
entity = get_character(entities, entities[key]['parent'])
4
except KeyError:
5
entity = {}
6
entity.update(entities[key])
7
return entity
8