Home > Software engineering >  Python: how parse this dict recursively?
Python: how parse this dict recursively?

Time:11-04

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:

  1. Each entity inherits defaults from its parent (e.g. is_mammal)
  2. Each entity can overwrite the defaults of its parent (e.g. age)
  3. Each entity can add new attributes (e.g. hobby)

I'm struggling to get it done. Help is appreciated, thanks!

entities = {
    'human': {
        'is_mammal': True,
        'age': None,
    },
    'man': {
        'parent': 'human', 
        'gender': 'male',
    },
    'john': {
        'parent': 'man',
        'age': 20,
        'hobby': 'football',
    }
};

def get_character(key):
    # ... recursive magic with entities ...
    return entity
    
john = get_character('john')
print(john)

Expected output:

{
    'is_mammal': True,  # inherited from human
    'gender': 'male'  # inherited from man
    'parent': 'man', 
    'age': 20, # overwritten
    'hobby': 'football', # added
}

CodePudding user response:

def get_character(entities, key):
    try:
        entity = get_character(entities, entities[key]['parent'])
    except KeyError:
        entity = {}
    entity.update(entities[key])
    return entity

CodePudding user response:

This solution is using recursion and a Python quirk where mutables (here it's a dictionary {}), are shared among function calls. See the discussion below for why this is somewhat surprising, though useful for accumulating recursion results.

def get_character(d, key, entity = {}):
    if d.get(key) is None:
        return entity
    return get_character(d, d.get(key).get('parent'), d.get(key) | entity)

get_character(entities, 'john')

{'is_mammal': True,
 'age': 20,
 'parent': 'man',
 'gender': 'male',
 'hobby': 'football'}
  • Related